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