Merge branch 'master' of git.freeside.biz:/home/git/freeside
[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'} ) {
614     # allow this to be an arrayref
615     my @values = ($params->{'address'});
616     @values = @{$values[0]} if ref($values[0]);
617     my @orwhere;
618     foreach (grep /\S/, @values) {
619       my $address = dbh->quote('%'. lc($_). '%');
620       push @orwhere,
621         "LOWER(cust_location.address1) LIKE $address",
622         "LOWER(cust_location.address2) LIKE $address";
623     }
624     if (@orwhere) {
625       push @where, "EXISTS(
626         SELECT 1 FROM cust_location 
627         WHERE cust_location.custnum = cust_main.custnum
628           AND (".join(' OR ',@orwhere).")
629         )";
630     }
631   }
632
633   ##
634   # zipcode
635   ##
636   if ( $params->{'zip'} =~ /\S/ ) {
637     my $zip = dbh->quote($params->{'zip'} . '%');
638     push @where, "EXISTS(
639       SELECT 1 FROM cust_location
640       WHERE cust_location.custnum = cust_main.custnum
641         AND cust_location.zip LIKE $zip
642     )";
643   }
644
645   ###
646   # refnum
647   ###
648   if ( $params->{'refnum'}  ) {
649
650     my @refnum = ref( $params->{'refnum'} )
651                    ? @{ $params->{'refnum'} }
652                    :  ( $params->{'refnum'} );
653
654     @refnum = grep /^(\d*)$/, @refnum;
655
656     push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
657       if @refnum;
658
659   }
660
661   ##
662   # parse cancelled package checkbox
663   ##
664
665   my $pkgwhere = "";
666
667   $pkgwhere .= "AND (cancel = 0 or cancel is null)"
668     unless $params->{'cancelled_pkgs'};
669
670   ##
671   # parse without census tract checkbox
672   ##
673
674   push @where, "(ship_location.censustract = '' or ship_location.censustract is null)"
675     if $params->{'no_censustract'};
676
677   ##
678   # parse with hardcoded tax location checkbox
679   ##
680
681   my $tax_prefix = FS::Conf->new->exists('tax-ship_location') ? 'ship_' 
682                                                               : 'bill_';
683   push @where, "${tax_prefix}location.geocode is not null"
684     if $params->{'with_geocode'};
685
686   ##
687   # "with email address(es)" checkbox
688   ##
689
690   push @where,
691     'EXISTS ( SELECT 1 FROM cust_main_invoice
692                 WHERE cust_main_invoice.custnum = cust_main.custnum
693                   AND length(dest) > 5
694             )'  # AND dest LIKE '%@%'
695     if $params->{'with_email'};
696
697   ##
698   # "with postal mail invoices" checkbox
699   ##
700
701   push @where,
702     "EXISTS ( SELECT 1 FROM cust_main_invoice
703                 WHERE cust_main_invoice.custnum = cust_main.custnum
704                   AND dest = 'POST' )"
705     if $params->{'POST'};
706
707   ##
708   # "without postal mail invoices" checkbox
709   ##
710
711   push @where,
712     "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
713                     WHERE cust_main_invoice.custnum = cust_main.custnum
714                       AND dest = 'POST' )"
715     if $params->{'no_POST'};
716
717   ##
718   # dates
719   ##
720
721   foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
722
723     next unless exists($params->{$field});
724
725     my($beginning, $ending, $hour) = @{$params->{$field}};
726
727     push @where,
728       "cust_main.$field IS NOT NULL",
729       "cust_main.$field >= $beginning",
730       "cust_main.$field <= $ending";
731
732     if($field eq 'signupdate' && defined $hour) {
733       if ($dbh->{Driver}->{Name} =~ /Pg/i) {
734         push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
735       }
736       elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
737         push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
738       }
739       else {
740         warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
741       }
742     }
743
744     $orderby ||= "ORDER BY cust_main.$field";
745
746   }
747
748   ###
749   # classnum
750   ###
751
752   if ( $params->{'classnum'} ) {
753
754     my @classnum = ref( $params->{'classnum'} )
755                      ? @{ $params->{'classnum'} }
756                      :  ( $params->{'classnum'} );
757
758     @classnum = grep /^(\d*)$/, @classnum;
759
760     if ( @classnum ) {
761       push @where, '( '. join(' OR ', map {
762                                             $_ ? "cust_main.classnum = $_"
763                                                : "cust_main.classnum IS NULL"
764                                           }
765                                           @classnum
766                              ).
767                    ' )';
768     }
769
770   }
771
772   ###
773   # payby
774   ###
775
776   if ( $params->{'payby'} ) {
777
778     my @payby = ref( $params->{'payby'} )
779                   ? @{ $params->{'payby'} }
780                   :  ( $params->{'payby'} );
781
782     @payby = grep /^([A-Z]{4})$/, @payby;
783
784     push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
785       if @payby;
786
787   }
788
789   ###
790   # paydate_year / paydate_month
791   ###
792
793   if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
794     my $year = $1;
795     $params->{'paydate_month'} =~ /^(\d\d?)$/
796       or die "paydate_year without paydate_month?";
797     my $month = $1;
798
799     push @where,
800       'paydate IS NOT NULL',
801       "paydate != ''",
802       "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
803 ;
804   }
805
806   ###
807   # invoice terms
808   ###
809
810   if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
811     my $terms = $1;
812     if ( $1 eq 'NULL' ) {
813       push @where,
814         "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
815     } else {
816       push @where,
817         "cust_main.invoice_terms IS NOT NULL",
818         "cust_main.invoice_terms = '$1'";
819     }
820   }
821
822   ##
823   # amounts
824   ##
825
826   if ( $params->{'current_balance'} ) {
827
828     #my $balance_sql = $class->balance_sql();
829     my $balance_sql = FS::cust_main->balance_sql();
830
831     my @current_balance =
832       ref( $params->{'current_balance'} )
833       ? @{ $params->{'current_balance'} }
834       :  ( $params->{'current_balance'} );
835
836     push @where, map { s/current_balance/$balance_sql/; $_ }
837                      @current_balance;
838
839   }
840
841   ##
842   # custbatch
843   ##
844
845   if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
846     push @where,
847       "cust_main.custbatch = '$1'";
848   }
849   
850   if ( $params->{'tagnum'} ) {
851     my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
852
853     @tagnums = grep /^(\d+)$/, @tagnums;
854
855     if ( @tagnums ) {
856       if ( $params->{'all_tags'} ) {
857         foreach ( @tagnums ) {
858           push @where, 'exists(select 1 from cust_tag where '.
859                        'cust_tag.custnum = cust_main.custnum and tagnum = '.
860                        $_ . ')';
861         }
862       } else { # matching any tag, not all
863         my $tags_where = "0 < (select count(1) from cust_tag where " 
864                 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
865                 . join(',', @tagnums) . "))";
866
867         push @where, $tags_where;
868       }
869     }
870   }
871
872
873   ##
874   # setup queries, subs, etc. for the search
875   ##
876
877   $orderby ||= 'ORDER BY custnum';
878
879   # here is the agent virtualization
880   push @where,
881     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
882
883   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
884
885   my $addl_from = '';
886   # always make address fields available in results
887   for my $pre ('bill_', 'ship_') {
888     $addl_from .= 
889       'LEFT JOIN cust_location AS '.$pre.'location '.
890       'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
891   }
892
893   my $count_query = "SELECT COUNT(*) FROM cust_main $addl_from $extra_sql";
894
895   my @select = (
896                  'cust_main.custnum',
897                  # there's a good chance that we'll need these
898                  'cust_main.bill_locationnum',
899                  'cust_main.ship_locationnum',
900                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
901                );
902
903   my(@extra_headers) = ();
904   my(@extra_fields)  = ();
905
906   if ($params->{'flattened_pkgs'}) {
907
908     #my $pkg_join = '';
909     $addl_from .=
910       ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
911
912     if ($dbh->{Driver}->{Name} eq 'Pg') {
913
914       push @select, "
915         ARRAY_TO_STRING(
916           ARRAY(
917             SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
918               WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
919           ), '|'
920         ) AS magic
921       ";
922
923     } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
924       push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
925       $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
926       #$pkg_join  .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
927     } else {
928       warn "warning: unknown database type ". $dbh->{Driver}->{Name}. 
929            "omitting package information from report.";
930     }
931
932     my $header_query = "
933       SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
934         FROM cust_main $addl_from $extra_sql $pkgwhere
935           GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
936     ";
937
938     my $sth = dbh->prepare($header_query) or die dbh->errstr;
939     $sth->execute() or die $sth->errstr;
940     my $headerrow = $sth->fetchrow_arrayref;
941     my $headercount = $headerrow ? $headerrow->[0] : 0;
942     while($headercount) {
943       unshift @extra_headers, "Package ". $headercount;
944       unshift @extra_fields, eval q!sub {my $c = shift;
945                                          my @a = split '\|', $c->magic;
946                                          my $p = $a[!.--$headercount. q!];
947                                          $p;
948                                         };!;
949     }
950
951   }
952
953   if ( $params->{'with_geocode'} ) {
954
955     unshift @extra_headers, 'Tax location override', 'Calculated tax location';
956     unshift @extra_fields, sub { my $c = shift; $c->get('geocode'); },
957                            sub { my $c = shift;
958                                  $c->set('geocode', '');
959                                  $c->geocode('cch'); #XXX only cch right now
960                                };
961     push @select, 'geocode';
962     push @select, 'zip' unless grep { $_ eq 'zip' } @select;
963     push @select, 'ship_zip' unless grep { $_ eq 'ship_zip' } @select;
964   }
965
966   my $select = join(', ', @select);
967
968   my $sql_query = {
969     'table'         => 'cust_main',
970     'select'        => $select,
971     'addl_from'     => $addl_from,
972     'hashref'       => {},
973     'extra_sql'     => $extra_sql,
974     'order_by'      => $orderby,
975     'count_query'   => $count_query,
976     'extra_headers' => \@extra_headers,
977     'extra_fields'  => \@extra_fields,
978   };
979   warn Data::Dumper::Dumper($sql_query);
980   $sql_query;
981
982 }
983
984 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
985
986 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
987 records.  Currently, I<first>, I<last>, I<company> and/or I<address1> may be
988 specified.
989
990 Additional options are the same as FS::Record::qsearch
991
992 =cut
993
994 sub fuzzy_search {
995   my $self = shift;
996   my $fuzzy = shift;
997   # sensible defaults, then merge in any passed options
998   my %fuzopts = (
999     'table'     => 'cust_main',
1000     'addl_from' => '',
1001     'extra_sql' => '',
1002     'hashref'   => {},
1003     @_
1004   );
1005
1006   my @cust_main = ();
1007
1008   my @fuzzy_mod = 'i';
1009   my $conf = new FS::Conf;
1010   my $fuzziness = $conf->config('fuzzy-fuzziness');
1011   push @fuzzy_mod, $fuzziness if $fuzziness;
1012
1013   check_and_rebuild_fuzzyfiles();
1014   foreach my $field ( keys %$fuzzy ) {
1015
1016     my $all = $self->all_X($field);
1017     next unless scalar(@$all);
1018
1019     my %match = ();
1020     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1021     next if !keys(%match);
1022
1023     my $in_matches = 'IN (' .
1024                      join(',', map { dbh->quote($_) } keys %match) .
1025                      ')';
1026
1027     my $extra_sql = $fuzopts{extra_sql};
1028     if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1029       $extra_sql .= ' AND ';
1030     } else {
1031       $extra_sql .= 'WHERE ';
1032     }
1033     $extra_sql .= "$field $in_matches";
1034
1035     my $addl_from = $fuzopts{addl_from};
1036     if ( $field =~ /^cust_location/ ) {
1037       $addl_from .= ' JOIN cust_location USING (custnum)';
1038     }
1039
1040     push @cust_main, qsearch({
1041       %fuzopts,
1042       'addl_from' => $addl_from,
1043       'extra_sql' => $extra_sql,
1044     });
1045   }
1046
1047   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1048   my %saw = ();
1049   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1050
1051   @cust_main;
1052
1053 }
1054
1055 =back
1056
1057 =head1 UTILITY SUBROUTINES
1058
1059 =over 4
1060
1061 =item check_and_rebuild_fuzzyfiles
1062
1063 =cut
1064
1065 sub check_and_rebuild_fuzzyfiles {
1066   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1067   rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields;
1068 }
1069
1070 =item rebuild_fuzzyfiles
1071
1072 =cut
1073
1074 sub rebuild_fuzzyfiles {
1075
1076   use Fcntl qw(:flock);
1077
1078   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1079   mkdir $dir, 0700 unless -d $dir;
1080
1081   foreach my $fuzzy ( @fuzzyfields ) {
1082
1083     my ($field, $table) = reverse split('\.', $fuzzy);
1084     $table ||= 'cust_main';
1085
1086     open(LOCK,">>$dir/$table.$field")
1087       or die "can't open $dir/$table.$field: $!";
1088     flock(LOCK,LOCK_EX)
1089       or die "can't lock $dir/$table.$field: $!";
1090
1091     open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1092       or die "can't open $dir/$table.$field.tmp: $!";
1093
1094     my $sth = dbh->prepare(
1095       "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1096     );
1097     $sth->execute or die $sth->errstr;
1098
1099     while ( my $row = $sth->fetchrow_arrayref ) {
1100       print CACHE $row->[0]. "\n";
1101     }
1102
1103     close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1104   
1105     rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1106     close LOCK;
1107   }
1108
1109 }
1110
1111 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1112
1113 =cut
1114
1115 sub append_fuzzyfiles {
1116   #my( $first, $last, $company ) = @_;
1117
1118   check_and_rebuild_fuzzyfiles();
1119
1120   use Fcntl qw(:flock);
1121
1122   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1123
1124   foreach my $fuzzy (@fuzzyfields) {
1125
1126     my ($field, $table) = reverse split('\.', $fuzzy);
1127     $table ||= 'cust_main';
1128
1129     my $value = shift;
1130
1131     if ( $value ) {
1132
1133       open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1134         or die "can't open $dir/$table.$field: $!";
1135       flock(CACHE,LOCK_EX)
1136         or die "can't lock $dir/$table.$field: $!";
1137
1138       print CACHE "$value\n";
1139
1140       flock(CACHE,LOCK_UN)
1141         or die "can't unlock $dir/$table.$field: $!";
1142       close CACHE;
1143     }
1144
1145   }
1146
1147   1;
1148 }
1149
1150 =item all_X
1151
1152 =cut
1153
1154 sub all_X {
1155   my( $self, $fuzzy ) = @_;
1156   my ($field, $table) = reverse split('\.', $fuzzy);
1157   $table ||= 'cust_main';
1158
1159   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1160   open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1161     or die "can't open $dir/$table.$field: $!";
1162   my @array = map { chomp; $_; } <CACHE>;
1163   close CACHE;
1164   \@array;
1165 }
1166
1167 =head1 BUGS
1168
1169 Bed bugs
1170
1171 =head1 SEE ALSO
1172
1173 L<FS::cust_main>, L<FS::Record>
1174
1175 =cut
1176
1177 1;
1178