default to a session cookie instead of setting an explicit timeout, weird timezone...
[freeside.git] / FS / FS / cust_main / Search.pm
1 package FS::cust_main::Search;
2
3 use strict;
4 use Carp qw( croak );
5 use base qw( Exporter );
6 use vars qw( @EXPORT_OK $DEBUG $me $conf @fuzzyfields );
7 use String::Approx qw(amatch);
8 use FS::UID qw( dbh );
9 use FS::Record qw( qsearch );
10 use FS::cust_main;
11 use FS::cust_main_invoice;
12 use FS::svc_acct;
13 use FS::payinfo_Mixin;
14
15 @EXPORT_OK = qw( smart_search );
16
17 # 1 is mostly method/subroutine entry and options
18 # 2 traces progress of some operations
19 # 3 is even more information including possibly sensitive data
20 $DEBUG = 0;
21 $me = '[FS::cust_main::Search]';
22
23 @fuzzyfields = (
24   'cust_main.first', 'cust_main.last', 'cust_main.company', 
25   'cust_main.ship_company', # if you're using it
26   'cust_location.address1',
27   'contact.first',   'contact.last',
28 );
29
30 install_callback FS::UID sub { 
31   $conf = new FS::Conf;
32   #yes, need it for stuff below (prolly should be cached)
33 };
34
35 =head1 NAME
36
37 FS::cust_main::Search - Customer searching
38
39 =head1 SYNOPSIS
40
41   use FS::cust_main::Search;
42
43   FS::cust_main::Search::smart_search(%options);
44
45   FS::cust_main::Search::email_search(%options);
46
47   FS::cust_main::Search->search( \%options );
48   
49   FS::cust_main::Search->fuzzy_search( \%fuzzy_hashref );
50
51 =head1 SUBROUTINES
52
53 =over 4
54
55 =item smart_search OPTION => VALUE ...
56
57 Accepts the following options: I<search>, the string to search for.  The string
58 will be searched for as a customer number, phone number, name or company name,
59 address (if address1-search is on), invoicing email address, or credit card
60 number.
61
62 Searches match as an exact, or, in some cases, a substring or fuzzy match (see
63 the source code for the exact heuristics used); I<no_fuzzy_on_exact>, causes
64 smart_search to
65 skip fuzzy matching when an exact match is found.
66
67 Any additional options are treated as an additional qualifier on the search
68 (i.e. I<agentnum>).
69
70 Returns a (possibly empty) array of FS::cust_main objects.
71
72 =cut
73
74 sub smart_search {
75   my %options = @_;
76
77   #here is the agent virtualization
78   my $agentnums_sql = 
79     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
80   my $agentnums_href = $FS::CurrentUser::CurrentUser->agentnums_href;
81
82   my @cust_main = ();
83
84   my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
85   my $search = delete $options{'search'};
86   ( my $alphanum_search = $search ) =~ s/\W//g;
87   
88   if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
89
90     #false laziness w/Record::ut_phone
91     my $phonen = "$1-$2-$3";
92     $phonen .= " x$4" if $4;
93
94     my $phonenum = "$1$2$3";
95     #my $extension = $4;
96
97     #cust_main phone numbers and contact phone number
98     push @cust_main, qsearch( {
99       'select'    => 'cust_main.*',
100       'table'     => 'cust_main',
101       'addl_from' => ' left join cust_contact  using (custnum) '.
102                      ' left join contact_phone using (contactnum) ',
103       'hashref'   => { %options },
104       'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
105                      ' ( '.
106                          join(' OR ', map "$_ = '$phonen'",
107                                           qw( daytime night mobile fax )
108                              ).
109                           " OR phonenum = '$phonenum' ".
110                      ' ) '.
111                      " AND $agentnums_sql", #agent virtualization
112     } );
113
114     unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
115       #try looking for matches with extensions unless one was specified
116
117       push @cust_main, qsearch( {
118         'table'     => 'cust_main',
119         'hashref'   => { %options },
120         'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
121                        ' ( '.
122                            join(' OR ', map "$_ LIKE '$phonen\%'",
123                                             qw( daytime night )
124                                ).
125                        ' ) '.
126                        " AND $agentnums_sql", #agent virtualization
127       } );
128
129     }
130
131   } 
132   
133   
134   if ( $search =~ /@/ ) { #email address from cust_main_invoice and contact_email
135
136     push @cust_main, qsearch( {
137       'select'    => 'cust_main.*',
138       'table'     => 'cust_main',
139       'addl_from' => ' left join cust_main_invoice using (custnum) '.
140                      ' left join cust_contact      using (custnum) '.
141                      ' left join contact_email     using (contactnum) ',
142       'hashref'   => { %options },
143       'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
144                      ' ( '.
145                          join(' OR ', map "$_ = '$search'",
146                                           qw( dest emailaddress )
147                              ).
148                      ' ) '.
149                      " AND $agentnums_sql", #agent virtualization
150     } );
151
152   # custnum search (also try agent_custid), with some tweaking options if your
153   # legacy cust "numbers" have letters
154   } elsif (    $search =~ /^\s*(\d+)\s*$/
155             or ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
156                  && $search =~ /^\s*(\w\w?\d+)\s*$/
157                )
158             or ( $conf->config('cust_main-agent_custid-format') eq 'd+-w'
159                  && $search =~ /^\s*(\d+-\w)\s*$/
160                )
161             or ( $conf->config('cust_main-custnum-display_special')
162                  # it's not currently possible for special prefixes to contain
163                  # digits, so just strip off any alphabetic prefix and match 
164                  # the rest to custnum
165                  && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
166                )
167             or ( $conf->exists('address1-search' )
168                  && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
169                )
170           )
171   {
172
173     my $num = $1;
174
175     if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
176       my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
177                                 ? ' AND agent_custid IS NULL ' : '';
178       push @cust_main, qsearch( {
179         'table'     => 'cust_main',
180         'hashref'   => { 'custnum' => $num, %options },
181         'extra_sql' => " AND $agentnums_sql $agent_custid_null",
182       } );
183     }
184
185     # for all agents this user can see, if any of them have custnum prefixes 
186     # that match the search string, include customers that match the rest 
187     # of the custnum and belong to that agent
188     foreach my $agentnum ( keys %$agentnums_href ) {
189       my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
190       next if !$p;
191       if ( $p eq substr($num, 0, length($p)) ) {
192         push @cust_main, qsearch( {
193           'table'   => 'cust_main',
194           'hashref' => { 'custnum' => 0 + substr($num, length($p)),
195                          'agentnum' => $agentnum,
196                           %options,
197                        },
198         } );
199       }
200     }
201
202     push @cust_main, qsearch( {
203         'table'     => 'cust_main',
204         'hashref'   => { 'agent_custid' => $num, %options },
205         'extra_sql' => " AND $agentnums_sql", #agent virtualization
206     } );
207
208     if ( $conf->exists('address1-search') ) {
209       my $len = length($num);
210       $num = lc($num);
211       # probably the Right Thing: return customers that have any associated
212       # locations matching the string, not just bill/ship location
213       push @cust_main, qsearch( {
214         'select'    => 'cust_main.*',
215         'table'     => 'cust_main',
216         'addl_from' => ' JOIN cust_location USING (custnum) ',
217         'hashref'   => { %options, },
218         'extra_sql' => 
219           ( keys(%options) ? ' AND ' : ' WHERE ' ).
220           " LOWER(SUBSTRING(cust_location.address1 FROM 1 FOR $len)) = '$num' ".
221           " AND $agentnums_sql",
222       } );
223     }
224
225   } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
226
227     my($company, $last, $first) = ( $1, $2, $3 );
228
229     # "Company (Last, First)"
230     #this is probably something a browser remembered,
231     #so just do an exact search (but case-insensitive, so USPS standardization
232     #doesn't throw a wrench in the works)
233
234     push @cust_main, qsearch( {
235       'table'     => 'cust_main',
236       'hashref'   => { %options },
237       'extra_sql' => 
238         ( keys(%options) ? ' AND ' : ' WHERE ' ).
239         join(' AND ',
240           " LOWER(first)   = ". dbh->quote(lc($first)),
241           " LOWER(last)    = ". dbh->quote(lc($last)),
242           " LOWER(company) = ". dbh->quote(lc($company)),
243           $agentnums_sql,
244         ),
245     } );
246
247     #contacts?
248     # probably not necessary for the "something a browser remembered" case
249
250   } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
251                                               # try {first,last,company}
252
253     my $value = lc($1);
254
255     # # remove "(Last, First)" in "Company (Last, First)", otherwise the
256     # # full strings the browser remembers won't work
257     # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
258
259     use Lingua::EN::NameParse;
260     my $NameParse = new Lingua::EN::NameParse(
261              auto_clean     => 1,
262              allow_reversed => 1,
263     );
264
265     my($last, $first) = ( '', '' );
266     #maybe disable this too and just rely on NameParse?
267     if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
268     
269       ($last, $first) = ( $1, $2 );
270     
271     #} elsif  ( $value =~ /^(.+)\s+(.+)$/ ) {
272     } elsif ( ! $NameParse->parse($value) ) {
273
274       my %name = $NameParse->components;
275       $first = lc($name{'given_name_1'}) || $name{'initials_1'}; #wtf NameParse, Ed?
276       $last  = lc($name{'surname_1'});
277
278     }
279
280     if ( $first && $last ) {
281
282       my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
283
284       #exact
285       my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
286       $sql .= "( (LOWER(cust_main.last) = $q_last AND LOWER(cust_main.first) = $q_first)
287                  OR (LOWER(contact.last) = $q_last AND LOWER(contact.first) = $q_first) )";
288
289       #cust_main and contacts
290       push @cust_main, qsearch( {
291         'select'    => 'cust_main.*',
292         'table'     => 'cust_main',
293         'addl_from' => ' left join cust_contact using (custnum) '.
294                        ' left join contact using (contactnum) ',
295         'hashref'   => { %options },
296         'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
297       } );
298
299       # or it just be something that was typed in... (try that in a sec)
300
301     }
302
303     my $q_value = dbh->quote($value);
304
305     #exact
306     my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
307     $sql .= " (    LOWER(cust_main.first)         = $q_value
308                 OR LOWER(cust_main.last)          = $q_value
309                 OR LOWER(cust_main.company)       = $q_value
310                 OR LOWER(cust_main.ship_company)  = $q_value
311                 OR LOWER(contact.first)           = $q_value
312                 OR LOWER(contact.last)            = $q_value
313             )";
314
315     #address1 (yes, it's a kludge)
316     $sql .= "   OR EXISTS ( 
317                             SELECT 1 FROM cust_location 
318                               WHERE LOWER(cust_location.address1) = $q_value
319                                 AND cust_location.custnum = cust_main.custnum
320                           )"
321       if $conf->exists('address1-search');
322
323     push @cust_main, qsearch( {
324       'select'    => 'cust_main.*',
325       'table'     => 'cust_main',
326       'addl_from' => ' left join cust_contact using (custnum) '.
327                      ' left join contact using (contactnum) ',
328       'hashref'   => { %options },
329       'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
330     } );
331
332     #no exact match, trying substring/fuzzy
333     #always do substring & fuzzy (unless they're explicity config'ed off)
334     #getting complaints searches are not returning enough
335     unless ( @cust_main  && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
336
337       #still some false laziness w/search (was search/cust_main.cgi)
338
339       my $min_len =
340         $FS::CurrentUser::CurrentUser->access_right('List all customers')
341         ? 3 : 4;
342
343       #substring
344
345       my @company_hashrefs = ();
346       if ( length($value) >= $min_len ) {
347         @company_hashrefs = (
348           { 'company'      => { op=>'ILIKE', value=>"%$value%" }, },
349           { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
350         );
351       }
352
353       my @hashrefs = ();
354       if ( $first && $last ) {
355
356         @hashrefs = (
357           { 'first'        => { op=>'ILIKE', value=>"%$first%" },
358             'last'         => { op=>'ILIKE', value=>"%$last%" },
359           },
360         );
361
362       } elsif ( length($value) >= $min_len ) {
363
364         @hashrefs = (
365           { 'first'        => { op=>'ILIKE', value=>"%$value%" }, },
366           { 'last'         => { op=>'ILIKE', value=>"%$value%" }, },
367         );
368
369       }
370
371       foreach my $hashref ( @company_hashrefs, @hashrefs ) {
372
373         push @cust_main, qsearch( {
374           'table'     => 'cust_main',
375           'hashref'   => { %$hashref,
376                            %options,
377                          },
378           'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
379         } );
380
381       }
382
383       if ( $conf->exists('address1-search') && length($value) >= $min_len ) {
384
385         push @cust_main, qsearch( {
386           select    => 'cust_main.*',
387           table     => 'cust_main',
388           addl_from => 'JOIN cust_location USING (custnum)',
389           extra_sql => 'WHERE '.
390                         ' cust_location.address1 ILIKE '.dbh->quote("%$value%").
391                         " AND $agentnums_sql", #agent virtualizaiton
392         } );
393
394       }
395
396       #contact substring
397
398       foreach my $hashref ( @hashrefs ) {
399
400         push @cust_main,
401           grep $agentnums_href->{$_->agentnum}, #agent virt
402             grep $_, #skip contacts that don't have cust_main records
403               map $_->cust_main,
404                 qsearch({
405                           'table'     => 'contact',
406                           'hashref'   => { %$hashref,
407                                            #%options,
408                                          },
409                           #'extra_sql' => " AND $agentnums_sql", #agent virt
410                        });
411
412       }
413
414       #fuzzy
415       my %fuzopts = (
416         'hashref'   => \%options,
417         'select'    => '',
418         'extra_sql' => "WHERE $agentnums_sql",    #agent virtualization
419       );
420
421       if ( $first && $last ) {
422         push @cust_main, FS::cust_main::Search->fuzzy_search(
423           { 'last'   => $last,    #fuzzy hashref
424             'first'  => $first }, #
425           %fuzopts
426         );
427         push @cust_main, FS::cust_main::Search->fuzzy_search(
428           { 'contact.last'   => $last,    #fuzzy hashref
429             'contact.first'  => $first }, #
430           %fuzopts
431         );
432       }
433
434       foreach my $field ( 'first', 'last', 'company', 'ship_company' ) {
435         push @cust_main, FS::cust_main::Search->fuzzy_search(
436           { $field => $value },
437           %fuzopts
438         );
439       }
440       foreach my $field ( 'first', 'last' ) {
441         push @cust_main, FS::cust_main::Search->fuzzy_search(
442           { "contact.$field" => $value },
443           %fuzopts
444         );
445       }
446       if ( $conf->exists('address1-search') ) {
447         push @cust_main,
448           FS::cust_main::Search->fuzzy_search(
449             { 'cust_location.address1' => $value },
450             %fuzopts
451         );
452       }
453
454     }
455
456   }
457
458   ( my $nospace_search = $search ) =~ s/\s//g;
459   ( my $card_search = $nospace_search ) =~ s/\-//g;
460   $card_search =~ s/[x\*\.\_]/x/gi;
461   
462   if ( $card_search =~ /^[\dx]{15,16}$/i ) { #credit card search
463
464     ( my $like_search = $card_search ) =~ s/x/_/g;
465     my $mask_search = FS::payinfo_Mixin->mask_payinfo('CARD', $card_search);
466
467     push @cust_main, qsearch({
468       'select'    => 'cust_main.*',
469       'table'     => 'cust_main',
470       'addl_from' => ' JOIN cust_payby USING (custnum)',
471       'hashref'   => {},
472       'extra_sql' => " WHERE (    cust_payby.payinfo LIKE '$like_search'
473                                OR cust_payby.paymask =    '$mask_search'
474                              ) ".
475                      " AND cust_payby.payby IN ('CARD','DCRD') ".
476                      " AND $agentnums_sql", #agent virtulization
477     });
478
479   }
480   
481
482   #eliminate duplicates
483   my %saw = ();
484   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
485
486   @cust_main;
487
488 }
489
490 =item email_search
491
492 Accepts the following options: I<email>, the email address to search for.  The
493 email address will be searched for as an email invoice destination and as an
494 svc_acct account.
495
496 #Any additional options are treated as an additional qualifier on the search
497 #(i.e. I<agentnum>).
498
499 Returns a (possibly empty) array of FS::cust_main objects (but usually just
500 none or one).
501
502 =cut
503
504 sub email_search {
505   my %options = @_;
506
507   my $email = delete $options{'email'};
508
509   #no agent virtualization yet
510   #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
511
512   my @cust_main = ();
513
514   if ( $email =~ /([^@]+)\@([^@]+)/ ) {
515
516     my ( $user, $domain ) = ( $1, $2 );
517
518     warn "$me smart_search: searching for $user in domain $domain"
519       if $DEBUG;
520
521     push @cust_main,
522       map { $_->cust_main }
523       map { $_->cust_contact }
524       map { $_->contact }
525           qsearch( {
526                      'table'     => 'contact_email',
527                      'hashref'   => { 'emailaddress' => $email },
528                    }
529                  );
530
531     push @cust_main,
532       map  $_->cust_main,
533       grep $_,
534       map  $_->cust_svc->cust_pkg,
535           qsearch( {
536                      'table'     => 'svc_acct',
537                      'hashref'   => { 'username' => $user, },
538                      'extra_sql' =>
539                        'AND ( SELECT domain FROM svc_domain
540                                 WHERE svc_acct.domsvc = svc_domain.svcnum
541                             ) = '. dbh->quote($domain),
542                    }
543                  );
544   }
545
546   my %saw = ();
547   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
548
549   warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
550     if $DEBUG;
551
552   @cust_main;
553
554 }
555
556 =back
557
558 =head1 CLASS METHODS
559
560 =over 4
561
562 =item search HASHREF
563
564 (Class method)
565
566 Returns a qsearch hash expression to search for parameters specified in
567 HASHREF.  Valid parameters are
568
569 =over 4
570
571 =item agentnum
572
573 =item status
574
575 =item address
576
577 =item zip
578
579 =item refnum
580
581 =item cancelled_pkgs
582
583 bool
584
585 =item signupdate
586
587 listref of start date, end date
588
589 =item birthdate
590
591 listref of start date, end date
592
593 =item spouse_birthdate
594
595 listref of start date, end date
596
597 =item anniversary_date
598
599 listref of start date, end date
600
601 =item current_balance
602
603 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
604
605 =item cust_fields
606
607 =item flattened_pkgs
608
609 bool
610
611 =back
612
613 =cut
614
615 sub search {
616   my ($class, $params) = @_;
617
618   my $dbh = dbh;
619
620   my @where = ();
621   my $orderby;
622
623   # initialize these to prevent warnings
624   $params = {
625     'custnum'       => '',
626     'agentnum'      => '',
627     'usernum'       => '',
628     'status'        => '',
629     'address'       => '',
630     'zip'           => '',
631     'invoice_terms' => '',
632     'custbatch'     => '',
633     %$params
634   };
635
636   ##
637   # explicit custnum(s)
638   ##
639
640   if ( $params->{'custnum'} ) {
641     my @custnums = ref($params->{'custnum'}) ? 
642                       @{ $params->{'custnum'} } : 
643                       $params->{'custnum'};
644     push @where, 
645       'cust_main.custnum IN (' . 
646       join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
647       ')' if scalar(@custnums) > 0;
648   }
649
650   ##
651   # parse agent
652   ##
653
654   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
655     push @where,
656       "cust_main.agentnum = $1";
657   }
658
659   ##
660   # parse sales person
661   ##
662
663   if ( $params->{'salesnum'} =~ /^(\d+)$/ ) {
664     push @where, ($1 > 0 ) ? "cust_main.salesnum = $1"
665                            : 'cust_main.salesnum IS NULL';
666   }
667
668   ##
669   # parse usernum
670   ##
671
672   if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
673     push @where,
674       "cust_main.usernum = $1";
675   }
676
677   ##
678   # parse status
679   ##
680
681   #prospect ordered active inactive suspended cancelled
682   if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
683     my $method = $params->{'status'}. '_sql';
684     #push @where, $class->$method();
685     push @where, FS::cust_main->$method();
686   }
687
688   my $current = '';
689   unless ( $params->{location_history} ) {
690     $current = '
691       AND (    cust_location.locationnum IN ( cust_main.bill_locationnum,
692                                               cust_main.ship_locationnum
693                                             )
694             OR cust_location.locationnum IN (
695                  SELECT locationnum FROM cust_pkg
696                   WHERE cust_pkg.custnum = cust_main.custnum
697                     AND locationnum IS NOT NULL
698                     AND '. FS::cust_pkg->ncancelled_recurring_sql.'
699                )
700           )';
701   }
702
703   ##
704   # address
705   ##
706   if ( $params->{'address'} ) {
707     # allow this to be an arrayref
708     my @values = ($params->{'address'});
709     @values = @{$values[0]} if ref($values[0]);
710     my @orwhere;
711     foreach (grep /\S/, @values) {
712       my $address = dbh->quote('%'. lc($_). '%');
713       push @orwhere,
714         "LOWER(cust_location.address1) LIKE $address",
715         "LOWER(cust_location.address2) LIKE $address";
716     }
717     if (@orwhere) {
718       push @where, "EXISTS(
719         SELECT 1 FROM cust_location 
720         WHERE cust_location.custnum = cust_main.custnum
721           AND (".join(' OR ',@orwhere).")
722           $current
723         )";
724     }
725   }
726
727   ##
728   # city
729   ##
730   if ( $params->{'city'} =~ /\S/ ) {
731     my $city = dbh->quote($params->{'city'});
732     push @where, "EXISTS(
733       SELECT 1 FROM cust_location
734       WHERE cust_location.custnum = cust_main.custnum
735         AND cust_location.city = $city
736         $current
737     )";
738   }
739
740   ##
741   # county
742   ##
743   if ( $params->{'county'} =~ /\S/ ) {
744     my $county = dbh->quote($params->{'county'});
745     push @where, "EXISTS(
746       SELECT 1 FROM cust_location
747       WHERE cust_location.custnum = cust_main.custnum
748         AND cust_location.county = $county
749         $current
750     )";
751   }
752
753   ##
754   # state
755   ##
756   if ( $params->{'state'} =~ /\S/ ) {
757     my $state = dbh->quote($params->{'state'});
758     push @where, "EXISTS(
759       SELECT 1 FROM cust_location
760       WHERE cust_location.custnum = cust_main.custnum
761         AND cust_location.state = $state
762         $current
763     )";
764   }
765
766   ##
767   # zipcode
768   ##
769   if ( $params->{'zip'} =~ /\S/ ) {
770     my $zip = dbh->quote($params->{'zip'} . '%');
771     push @where, "EXISTS(
772       SELECT 1 FROM cust_location
773       WHERE cust_location.custnum = cust_main.custnum
774         AND cust_location.zip LIKE $zip
775         $current
776     )";
777   }
778
779   ##
780   # country
781   ##
782   if ( $params->{'country'} =~ /^(\w\w)$/ ) {
783     my $country = uc($1);
784     push @where, "EXISTS(
785       SELECT 1 FROM cust_location
786       WHERE cust_location.custnum = cust_main.custnum
787         AND cust_location.country = '$country'
788         $current
789     )";
790   }
791
792   ##
793   # no_censustract
794   ##
795   if ( $params->{'no_censustract'} ) {
796     push @where, "EXISTS(
797       SELECT 1 FROM cust_location
798       WHERE locationnum = cust_main.ship_locationnum
799         AND cust_location.country = 'US'
800         AND (    cust_location.censusyear IS NULL
801               OR cust_location.censusyear != '2020'
802             )
803     )";
804   }
805
806   ##
807   # phones
808   ##
809
810   foreach my $phonet (qw(daytime night mobile fax)) {
811     if ($params->{$phonet}) {
812       $params->{$phonet} =~ s/\D//g;
813       $params->{$phonet} =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/
814         or next;
815       my $phonen = "$1-$2-$3";
816       if ($4) { push @where, "cust_main.".$phonet." = '".$phonen." x$4'"; }
817       else { push @where, "cust_main.".$phonet." like '".$phonen."%'"; }
818     }
819   }
820
821   ###
822   # refnum
823   ###
824   if ( $params->{'refnum'}  ) {
825
826     my @refnum = ref( $params->{'refnum'} )
827                    ? @{ $params->{'refnum'} }
828                    :  ( $params->{'refnum'} );
829
830     @refnum = grep /^(\d*)$/, @refnum;
831
832     push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
833       if @refnum;
834
835   }
836
837   ##
838   # parse cancelled package checkbox
839   ##
840
841   my $pkgwhere = "";
842
843   $pkgwhere .= "AND (cancel = 0 or cancel is null)"
844     unless $params->{'cancelled_pkgs'};
845
846   ##
847   # "with email address(es)" checkbox,
848   #    also optionally: with_email_dest and with_contact_type
849   ##
850
851   if ($params->{with_email}) {
852     my @email_dest;
853     my $email_dest_sql;
854     my $contact_type_sql;
855
856     if ($params->{with_email_dest}) {
857       croak unless ref $params->{with_email_dest} eq 'ARRAY';
858
859       @email_dest = @{$params->{with_email_dest}};
860       $email_dest_sql =
861         " AND ( ".
862         join(' OR ',map(" cust_contact.${_}_dest IS NOT NULL ", @email_dest)).
863         " ) ";
864         # Can't use message_dist = 'Y' because single quotes are escaped later
865     }
866     if ($params->{with_contact_type}) {
867       croak unless ref $params->{with_contact_type} eq 'ARRAY';
868
869       my @contact_type = grep {/^\d+$/ && $_ > 0} @{$params->{with_contact_type}};
870       my $has_null_type = 0;
871       $has_null_type = 1 if grep { $_ eq 0 } @{$params->{with_contact_type}};
872       my $hnt_sql;
873       if ($has_null_type) {
874         $hnt_sql  = ' OR ' if @contact_type;
875         $hnt_sql .= ' cust_contact.classnum IS NULL ';
876       }
877
878       $contact_type_sql =
879         " AND ( ".
880         join(' OR ', map(" cust_contact.classnum = $_ ", @contact_type)).
881         $hnt_sql.
882         " ) ";
883     }
884     push @where,
885       "EXISTS ( SELECT 1 FROM contact_email
886                 JOIN cust_contact USING (contactnum)
887                 WHERE cust_contact.custnum = cust_main.custnum
888                 $email_dest_sql
889                 $contact_type_sql
890               ) ";
891   }
892
893   ##
894   # "with postal mail invoices" checkbox
895   ##
896
897   push @where, "cust_main.postal_invoice = 'Y'"
898     if $params->{'POST'};
899
900   ##
901   # "without postal mail invoices" checkbox
902   ##
903
904   push @where, "cust_main.postal_invoice IS NULL"
905     if $params->{'no_POST'};
906
907   ##
908   # "tax exempt" checkbox
909   ##
910   push @where, "cust_main.tax = 'Y'"
911     if $params->{'tax'};
912
913   ##
914   # "not tax exempt" checkbox
915   ##
916   push @where, "(cust_main.tax = '' OR cust_main.tax IS NULL )"
917     if $params->{'no_tax'};
918
919   ##
920   # with referrals
921   ##
922   if ( $params->{with_referrals} =~ /^\s*(\d+)\s*$/ ) {
923
924     my $n = $1;
925   
926     # referral status
927     my $and_status = '';
928     if ( grep { $params->{referral_status} eq $_ } FS::cust_main->statuses() ) {
929       my $method = $params->{referral_status}. '_sql';
930       $and_status = ' AND '. FS::cust_main->$method();
931       $and_status =~ s/ cust_main\./ referred_cust_main./g;
932     }
933
934     push @where,
935       " $n <= ( SELECT COUNT(*) FROM cust_main AS referred_cust_main
936                   WHERE cust_main.custnum = referred_cust_main.referral_custnum
937                     $and_status
938               )";
939
940   }
941
942   ##
943   # dates
944   ##
945
946   foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
947
948     next unless exists($params->{$field});
949
950     my($beginning, $ending, $hour) = @{$params->{$field}};
951
952     push @where,
953       "cust_main.$field IS NOT NULL",
954       "cust_main.$field >= $beginning",
955       "cust_main.$field <= $ending";
956
957     if($field eq 'signupdate' && defined $hour) {
958       if ($dbh->{Driver}->{Name} =~ /Pg/i) {
959         push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
960       }
961       elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
962         push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
963       }
964       else {
965         warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
966       }
967     }
968
969     $orderby ||= "ORDER BY cust_main.$field";
970
971   }
972
973   ###
974   # classnum
975   ###
976
977   if ( $params->{'classnum'} ) {
978
979     my @classnum = ref( $params->{'classnum'} )
980                      ? @{ $params->{'classnum'} }
981                      :  ( $params->{'classnum'} );
982
983     @classnum = grep /^(\d*)$/, @classnum;
984
985     if ( @classnum ) {
986       push @where, '( '. join(' OR ', map {
987                                             $_ ? "cust_main.classnum = $_"
988                                                : "cust_main.classnum IS NULL"
989                                           }
990                                           @classnum
991                              ).
992                    ' )';
993     }
994
995   }
996
997   ###
998   # invoice terms
999   ###
1000
1001   if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
1002     my $terms = $1;
1003     if ( $1 eq 'NULL' ) {
1004       push @where,
1005         "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
1006     } else {
1007       push @where,
1008         "cust_main.invoice_terms IS NOT NULL",
1009         "cust_main.invoice_terms = '$1'";
1010     }
1011   }
1012
1013   ##
1014   # amounts
1015   ##
1016
1017   if ( $params->{'current_balance'} ) {
1018
1019     #my $balance_sql = $class->balance_sql();
1020     my $balance_sql = FS::cust_main->balance_sql();
1021
1022     my @current_balance =
1023       ref( $params->{'current_balance'} )
1024       ? @{ $params->{'current_balance'} }
1025       :  ( $params->{'current_balance'} );
1026
1027     push @where, map { s/current_balance/$balance_sql/; $_ }
1028                      @current_balance;
1029
1030   }
1031
1032   ##
1033   # custbatch
1034   ##
1035
1036   if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
1037     push @where,
1038       "cust_main.custbatch = '$1'";
1039   }
1040   
1041   if ( $params->{'tagnum'} ) {
1042     my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
1043
1044     @tagnums = grep /^(\d+)$/, @tagnums;
1045
1046     if ( @tagnums ) {
1047       if ( $params->{'all_tags'} ) {
1048         my $exists = $params->{'all_tags'} eq 'all' ? 'exists' : 'not exists';
1049         foreach ( @tagnums ) {
1050           push @where, $exists.'(select 1 from cust_tag where '.
1051                        'cust_tag.custnum = cust_main.custnum and tagnum = '.
1052                        $_ . ')';
1053         }
1054       } else { # matching any tag, not all
1055         my $tags_where = "0 < (select count(1) from cust_tag where " 
1056                 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
1057                 . join(',', @tagnums) . "))";
1058
1059         push @where, $tags_where;
1060       }
1061     }
1062   }
1063
1064   # pkg_classnum
1065   #   all_pkg_classnums
1066   #   any_pkg_status
1067   if ( $params->{'pkg_classnum'} ) {
1068     my @pkg_classnums = ref( $params->{'pkg_classnum'} ) ?
1069                           @{ $params->{'pkg_classnum'} } :
1070                              $params->{'pkg_classnum'};
1071     @pkg_classnums = grep /^(\d+)$/, @pkg_classnums;
1072
1073     if ( @pkg_classnums ) {
1074
1075       my @pkg_where;
1076       if ( $params->{'all_pkg_classnums'} ) {
1077         push @pkg_where, "part_pkg.classnum = $_" foreach @pkg_classnums;
1078       } else {
1079         push @pkg_where,
1080           'part_pkg.classnum IN('. join(',', @pkg_classnums).')';
1081       }
1082       foreach (@pkg_where) {
1083         my $select_pkg = 
1084           "SELECT 1 FROM cust_pkg JOIN part_pkg USING (pkgpart) WHERE ".
1085           "cust_pkg.custnum = cust_main.custnum AND $_ ";
1086         if ( not $params->{'any_pkg_status'} ) {
1087           $select_pkg .= 'AND '.FS::cust_pkg->active_sql;
1088         }
1089         push @where, "EXISTS($select_pkg)";
1090       }
1091     }
1092   }
1093
1094   ##
1095   # contacts
1096   ##
1097   if (keys %{ $params->{'contacts'} }) {
1098     my $contact_params = $params->{'contacts'};
1099
1100     if ($contact_params->{'contacts_firstname'} || $contact_params->{'contacts_lastname'}) {
1101       my $first_query = " AND contact.first = '" . $contact_params->{'contacts_firstname'} . "'"
1102         unless !$contact_params->{'contacts_firstname'};
1103       my $last_query = " AND contact.last = '" . $contact_params->{'contacts_lastname'} . "'"
1104         unless !$contact_params->{'contacts_lastname'};
1105       push @where,
1106       "EXISTS ( SELECT 1 FROM contact
1107                 JOIN cust_contact USING (contactnum)
1108                 WHERE cust_contact.custnum = cust_main.custnum
1109                 $first_query $last_query
1110               ) ";
1111     }
1112
1113     if ($contact_params->{'contacts_email'}) {
1114       push @where,
1115       "EXISTS ( SELECT 1 FROM contact_email
1116                 JOIN cust_contact USING (contactnum)
1117                 WHERE cust_contact.custnum = cust_main.custnum
1118                 AND contact_email.emailaddress = '" . $contact_params->{'contacts_email'} . "'
1119               ) ";
1120     }
1121
1122     if ( grep { /^contacts_phonetypenum(\d+)$/ } keys %{ $contact_params } ) {
1123       my $phone_query;
1124       foreach my $phone ( grep { /^contacts_phonetypenum(\d+)$/ } keys %{ $contact_params } ) {
1125         $phone =~ /^contacts_phonetypenum(\d+)$/ or die "No phone type num $1 from $phone";
1126         my $phonetypenum = $1;
1127         (my $num = $contact_params->{$phone}) =~ s/\W//g;
1128         if ( $num =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { $contact_params->{$phone} = "$1$2$3"; }
1129         $phone_query .= " AND ( contact_phone.phonetypenum = '".$phonetypenum."' AND contact_phone.phonenum = '" . $contact_params->{$phone} . "' )"
1130         unless !$contact_params->{$phone};
1131       }
1132       push @where,
1133       "EXISTS ( SELECT 1 FROM contact_phone
1134                 JOIN cust_contact USING (contactnum)
1135                 WHERE cust_contact.custnum = cust_main.custnum
1136                 $phone_query
1137               ) ";
1138     }
1139   }
1140
1141
1142   ##
1143   # setup queries, subs, etc. for the search
1144   ##
1145
1146   $orderby ||= 'ORDER BY cust_main.custnum';
1147
1148   # here is the agent virtualization
1149   push @where,
1150     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
1151
1152   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
1153
1154   my $addl_from = '';
1155   # always make address fields available in results
1156   for my $pre ('bill_', 'ship_') {
1157     $addl_from .= 
1158       'LEFT JOIN cust_location AS '.$pre.'location '.
1159       'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
1160   }
1161
1162   # always make referral available in results
1163   #   (maybe we should be using FS::UI::Web::join_cust_main instead?)
1164   $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
1165
1166   my @select = (
1167                  'cust_main.custnum',
1168                  'cust_main.salesnum',
1169                  # there's a good chance that we'll need these
1170                  'cust_main.bill_locationnum',
1171                  'cust_main.ship_locationnum',
1172                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
1173                );
1174
1175   my @extra_headers     = ();
1176   my @extra_fields      = ();
1177   my @extra_sort_fields = ();
1178
1179   my $count_query = "SELECT COUNT(DISTINCT cust_main.custnum) FROM cust_main $addl_from $extra_sql";
1180
1181   if ($params->{'flattened_pkgs'}) {
1182
1183     #my $pkg_join = '';
1184     $addl_from .=
1185       ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
1186
1187     if ($dbh->{Driver}->{Name} eq 'Pg') {
1188
1189       push @select, "
1190         ARRAY_TO_STRING(
1191           ARRAY(
1192             SELECT pkg FROM cust_pkg LEFT JOIN part_pkg USING ( pkgpart )
1193               WHERE cust_main.custnum = cust_pkg.custnum $pkgwhere
1194           ), '|'
1195         ) AS magic
1196       ";
1197
1198     } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
1199       push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
1200       $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1201       #$pkg_join  .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
1202     } else {
1203       warn "warning: unknown database type ". $dbh->{Driver}->{Name}. 
1204            "omitting package information from report.";
1205     }
1206
1207     my $header_query = "
1208       SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count
1209         FROM cust_main $addl_from $extra_sql $pkgwhere
1210           GROUP BY cust_main.custnum ORDER BY count DESC LIMIT 1
1211     ";
1212
1213     my $sth = dbh->prepare($header_query) or die dbh->errstr;
1214     $sth->execute() or die $sth->errstr;
1215     my $headerrow = $sth->fetchrow_arrayref;
1216     my $headercount = $headerrow ? $headerrow->[0] : 0;
1217     while($headercount) {
1218       unshift @extra_headers, "Package ". $headercount;
1219       unshift @extra_fields, eval q!sub {my $c = shift;
1220                                          my @a = split '\|', $c->magic;
1221                                          my $p = $a[!.--$headercount. q!];
1222                                          $p;
1223                                         };!;
1224       unshift @extra_sort_fields, '';
1225     }
1226
1227   }
1228
1229   if ( $params->{'with_referrals'} ) {
1230
1231     #XXX next: num for each customer status
1232      
1233     push @select,
1234       '( SELECT COUNT(*) FROM cust_main AS referred_cust_main
1235            WHERE cust_main.custnum = referred_cust_main.referral_custnum
1236        ) AS num_referrals';
1237
1238     unshift @extra_headers, 'Referrals';
1239     unshift @extra_fields, 'num_referrals';
1240     unshift @extra_sort_fields, 'num_referrals';
1241
1242   }
1243
1244   my $select = join(', ', @select);
1245
1246   my $sql_query = {
1247     'table'             => 'cust_main',
1248     'select'            => $select,
1249     'addl_from'         => $addl_from,
1250     'hashref'           => {},
1251     'extra_sql'         => $extra_sql,
1252     'order_by'          => $orderby,
1253     'count_query'       => $count_query,
1254     'extra_headers'     => \@extra_headers,
1255     'extra_fields'      => \@extra_fields,
1256     'extra_sort_fields' => \@extra_sort_fields,
1257   };
1258   $sql_query;
1259
1260 }
1261
1262 =item fuzzy_search FUZZY_HASHREF [ OPTS ]
1263
1264 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
1265 records.  Currently, I<first>, I<last>, I<company> and/or I<address1> may be
1266 specified.
1267
1268 Additional options are the same as FS::Record::qsearch
1269
1270 =cut
1271
1272 sub fuzzy_search {
1273   my $self = shift;
1274   my $fuzzy = shift;
1275   # sensible defaults, then merge in any passed options
1276   my %fuzopts = (
1277     'table'     => 'cust_main',
1278     'addl_from' => '',
1279     'extra_sql' => '',
1280     'hashref'   => {},
1281     @_
1282   );
1283
1284   my @cust_main = ();
1285
1286   my @fuzzy_mod = 'i';
1287   my $conf = new FS::Conf;
1288   my $fuzziness = $conf->config('fuzzy-fuzziness');
1289   push @fuzzy_mod, $fuzziness if $fuzziness;
1290
1291   check_and_rebuild_fuzzyfiles();
1292   foreach my $field ( keys %$fuzzy ) {
1293
1294     my $all = $self->all_X($field);
1295     next unless scalar(@$all);
1296
1297     my %match = ();
1298     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, \@fuzzy_mod, @$all ) );
1299     next if !keys(%match);
1300
1301     my $in_matches = 'IN (' .
1302                      join(',', map { dbh->quote($_) } keys %match) .
1303                      ')';
1304
1305     my $extra_sql = $fuzopts{extra_sql};
1306     if ($extra_sql =~ /^\s*where /i or keys %{ $fuzopts{hashref} }) {
1307       $extra_sql .= ' AND ';
1308     } else {
1309       $extra_sql .= 'WHERE ';
1310     }
1311     $extra_sql .= "$field $in_matches";
1312
1313     my $addl_from = $fuzopts{addl_from};
1314     if ( $field =~ /^cust_location\./ ) {
1315       $addl_from .= ' JOIN cust_location USING (custnum)';
1316     } elsif ( $field =~ /^contact\./ ) {
1317       $addl_from .= ' JOIN contact USING (custnum)';
1318     }
1319
1320     push @cust_main, qsearch({
1321       %fuzopts,
1322       'addl_from' => $addl_from,
1323       'extra_sql' => $extra_sql,
1324     });
1325   }
1326
1327   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
1328   my %saw = ();
1329   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
1330
1331   @cust_main;
1332
1333 }
1334
1335 =back
1336
1337 =head1 UTILITY SUBROUTINES
1338
1339 =over 4
1340
1341 =item check_and_rebuild_fuzzyfiles
1342
1343 =cut
1344
1345 sub check_and_rebuild_fuzzyfiles {
1346   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1347   rebuild_fuzzyfiles()
1348     if grep { ! -e "$dir/$_" }
1349          map {
1350                my ($field, $table) = reverse split('\.', $_);
1351                $table ||= 'cust_main';
1352                "$table.$field"
1353              }
1354            @fuzzyfields;
1355 }
1356
1357 =item rebuild_fuzzyfiles
1358
1359 =cut
1360
1361 sub rebuild_fuzzyfiles {
1362
1363   use Fcntl qw(:flock);
1364
1365   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1366   mkdir $dir, 0700 unless -d $dir;
1367
1368   foreach my $fuzzy ( @fuzzyfields ) {
1369
1370     my ($field, $table) = reverse split('\.', $fuzzy);
1371     $table ||= 'cust_main';
1372
1373     open(LOCK,">>$dir/$table.$field")
1374       or die "can't open $dir/$table.$field: $!";
1375     flock(LOCK,LOCK_EX)
1376       or die "can't lock $dir/$table.$field: $!";
1377
1378     open (CACHE, '>:encoding(UTF-8)', "$dir/$table.$field.tmp")
1379       or die "can't open $dir/$table.$field.tmp: $!";
1380
1381     my $sth = dbh->prepare(
1382       "SELECT $field FROM $table WHERE $field IS NOT NULL AND $field != ''"
1383     );
1384     $sth->execute or die $sth->errstr;
1385
1386     while ( my $row = $sth->fetchrow_arrayref ) {
1387       print CACHE $row->[0]. "\n";
1388     }
1389
1390     close CACHE or die "can't close $dir/$table.$field.tmp: $!";
1391   
1392     rename "$dir/$table.$field.tmp", "$dir/$table.$field";
1393     close LOCK;
1394   }
1395
1396 }
1397
1398 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
1399
1400 =cut
1401
1402 sub append_fuzzyfiles {
1403   #my( $first, $last, $company ) = @_;
1404
1405   check_and_rebuild_fuzzyfiles();
1406
1407   #foreach my $fuzzy (@fuzzyfields) {
1408   foreach my $fuzzy ( 'cust_main.first', 'cust_main.last', 'cust_main.company', 
1409                       'cust_location.address1',
1410                       'cust_main.ship_company',
1411                     ) {
1412
1413     append_fuzzyfiles_fuzzyfield($fuzzy, shift);
1414
1415   }
1416
1417   1;
1418 }
1419
1420 =item append_fuzzyfiles_fuzzyfield COLUMN VALUE
1421
1422 =item append_fuzzyfiles_fuzzyfield TABLE.COLUMN VALUE
1423
1424 =cut
1425
1426 use Fcntl qw(:flock);
1427 sub append_fuzzyfiles_fuzzyfield {
1428   my( $fuzzyfield, $value ) = @_;
1429
1430   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1431
1432
1433   my ($field, $table) = reverse split('\.', $fuzzyfield);
1434   $table ||= 'cust_main';
1435
1436   return unless defined($value) && length($value);
1437
1438   open(CACHE, '>>:encoding(UTF-8)', "$dir/$table.$field" )
1439     or die "can't open $dir/$table.$field: $!";
1440   flock(CACHE,LOCK_EX)
1441     or die "can't lock $dir/$table.$field: $!";
1442
1443   print CACHE "$value\n";
1444
1445   flock(CACHE,LOCK_UN)
1446     or die "can't unlock $dir/$table.$field: $!";
1447   close CACHE;
1448
1449 }
1450
1451 =item all_X
1452
1453 =cut
1454
1455 sub all_X {
1456   my( $self, $fuzzy ) = @_;
1457   my ($field, $table) = reverse split('\.', $fuzzy);
1458   $table ||= 'cust_main';
1459
1460   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1461   open(CACHE, '<:encoding(UTF-8)', "$dir/$table.$field")
1462     or die "can't open $dir/$table.$field: $!";
1463   my @array = map { chomp; $_; } <CACHE>;
1464   close CACHE;
1465   \@array;
1466 }
1467
1468 =head1 BUGS
1469
1470 Bed bugs
1471
1472 =head1 SEE ALSO
1473
1474 L<FS::cust_main>, L<FS::Record>
1475
1476 =cut
1477
1478 1;