This commit was manufactured by cvs2svn to create tag 'freeside_2_1_1'.
[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
13 @EXPORT_OK = qw( smart_search );
14
15 # 1 is mostly method/subroutine entry and options
16 # 2 traces progress of some operations
17 # 3 is even more information including possibly sensitive data
18 $DEBUG = 0;
19 $me = '[FS::cust_main::Search]';
20
21 @fuzzyfields = @FS::cust_main::fuzzyfields;
22
23 install_callback FS::UID sub { 
24   $conf = new FS::Conf;
25   #yes, need it for stuff below (prolly should be cached)
26 };
27
28 =head1 NAME
29
30 FS::cust_main::Search - Customer searching
31
32 =head1 SYNOPSIS
33
34   use FS::cust_main::Search;
35
36   FS::cust_main::Search::smart_search(%options);
37
38   FS::cust_main::Search::email_search(%options);
39
40   FS::cust_main::Search->search( \%options );
41   
42   FS::cust_main::Search->fuzzy_search( \%fuzzy_hashref );
43
44 =head1 SUBROUTINES
45
46 =over 4
47
48 =item smart_search OPTION => VALUE ...
49
50 Accepts the following options: I<search>, the string to search for.  The string
51 will be searched for as a customer number, phone number, name or company name,
52 as an exact, or, in some cases, a substring or fuzzy match (see the source code
53 for the exact heuristics used); I<no_fuzzy_on_exact>, causes smart_search to
54 skip fuzzy matching when an exact match is found.
55
56 Any additional options are treated as an additional qualifier on the search
57 (i.e. I<agentnum>).
58
59 Returns a (possibly empty) array of FS::cust_main objects.
60
61 =cut
62
63 sub smart_search {
64   my %options = @_;
65
66   #here is the agent virtualization
67   my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
68
69   my @cust_main = ();
70
71   my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
72   my $search = delete $options{'search'};
73   ( my $alphanum_search = $search ) =~ s/\W//g;
74   
75   if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
76
77     #false laziness w/Record::ut_phone
78     my $phonen = "$1-$2-$3";
79     $phonen .= " x$4" if $4;
80
81     push @cust_main, qsearch( {
82       'table'   => 'cust_main',
83       'hashref' => { %options },
84       'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
85                      ' ( '.
86                          join(' OR ', map "$_ = '$phonen'",
87                                           qw( daytime night fax
88                                               ship_daytime ship_night ship_fax )
89                              ).
90                      ' ) '.
91                      " AND $agentnums_sql", #agent virtualization
92     } );
93
94     unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
95       #try looking for matches with extensions unless one was specified
96
97       push @cust_main, qsearch( {
98         'table'   => 'cust_main',
99         'hashref' => { %options },
100         'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
101                        ' ( '.
102                            join(' OR ', map "$_ LIKE '$phonen\%'",
103                                             qw( daytime night
104                                                 ship_daytime ship_night )
105                                ).
106                        ' ) '.
107                        " AND $agentnums_sql", #agent virtualization
108       } );
109
110     }
111
112   # custnum search (also try agent_custid), with some tweaking options if your
113   # legacy cust "numbers" have letters
114   } 
115
116   if ( $search =~ /^\s*(\d+)\s*$/
117          || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
118               && $search =~ /^\s*(\w\w?\d+)\s*$/
119             )
120          || ( $conf->exists('address1-search' )
121               && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
122             )
123      )
124   {
125
126     my $num = $1;
127
128     if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
129       push @cust_main, qsearch( {
130         'table'     => 'cust_main',
131         'hashref'   => { 'custnum' => $num, %options },
132         'extra_sql' => " AND $agentnums_sql", #agent virtualization
133       } );
134     }
135
136     push @cust_main, qsearch( {
137       'table'     => 'cust_main',
138       'hashref'   => { 'agent_custid' => $num, %options },
139       'extra_sql' => " AND $agentnums_sql", #agent virtualization
140     } );
141
142     if ( $conf->exists('address1-search') ) {
143       my $len = length($num);
144       $num = lc($num);
145       foreach my $prefix ( '', 'ship_' ) {
146         push @cust_main, qsearch( {
147           'table'     => 'cust_main',
148           'hashref'   => { %options, },
149           'extra_sql' => 
150             ( keys(%options) ? ' AND ' : ' WHERE ' ).
151             " LOWER(SUBSTRING(${prefix}address1 FROM 1 FOR $len)) = '$num' ".
152             " AND $agentnums_sql",
153         } );
154       }
155     }
156
157   } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
158
159     my($company, $last, $first) = ( $1, $2, $3 );
160
161     # "Company (Last, First)"
162     #this is probably something a browser remembered,
163     #so just do an exact search (but case-insensitive, so USPS standardization
164     #doesn't throw a wrench in the works)
165
166     foreach my $prefix ( '', 'ship_' ) {
167       push @cust_main, qsearch( {
168         'table'     => 'cust_main',
169         'hashref'   => { %options },
170         'extra_sql' => 
171           ( keys(%options) ? ' AND ' : ' WHERE ' ).
172           join(' AND ',
173             " LOWER(${prefix}first)   = ". dbh->quote(lc($first)),
174             " LOWER(${prefix}last)    = ". dbh->quote(lc($last)),
175             " LOWER(${prefix}company) = ". dbh->quote(lc($company)),
176             $agentnums_sql,
177           ),
178       } );
179     }
180
181   } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
182                                               # try (ship_){last,company}
183
184     my $value = lc($1);
185
186     # # remove "(Last, First)" in "Company (Last, First)", otherwise the
187     # # full strings the browser remembers won't work
188     # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
189
190     use Lingua::EN::NameParse;
191     my $NameParse = new Lingua::EN::NameParse(
192              auto_clean     => 1,
193              allow_reversed => 1,
194     );
195
196     my($last, $first) = ( '', '' );
197     #maybe disable this too and just rely on NameParse?
198     if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
199     
200       ($last, $first) = ( $1, $2 );
201     
202     #} elsif  ( $value =~ /^(.+)\s+(.+)$/ ) {
203     } elsif ( ! $NameParse->parse($value) ) {
204
205       my %name = $NameParse->components;
206       $first = $name{'given_name_1'};
207       $last  = $name{'surname_1'};
208
209     }
210
211     if ( $first && $last ) {
212
213       my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
214
215       #exact
216       my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
217       $sql .= "
218         (     ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
219            OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
220         )";
221
222       push @cust_main, qsearch( {
223         'table'     => 'cust_main',
224         'hashref'   => \%options,
225         'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
226       } );
227
228       # or it just be something that was typed in... (try that in a sec)
229
230     }
231
232     my $q_value = dbh->quote($value);
233
234     #exact
235     my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
236     $sql .= " (    LOWER(last)          = $q_value
237                 OR LOWER(company)       = $q_value
238                 OR LOWER(ship_last)     = $q_value
239                 OR LOWER(ship_company)  = $q_value
240             ";
241     $sql .= "   OR LOWER(address1)      = $q_value
242                 OR LOWER(ship_address1) = $q_value
243             "
244       if $conf->exists('address1-search');
245     $sql .= " )";
246
247     push @cust_main, qsearch( {
248       'table'     => 'cust_main',
249       'hashref'   => \%options,
250       'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
251     } );
252
253     #no exact match, trying substring/fuzzy
254     #always do substring & fuzzy (unless they're explicity config'ed off)
255     #getting complaints searches are not returning enough
256     unless ( @cust_main  && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
257
258       #still some false laziness w/search (was search/cust_main.cgi)
259
260       #substring
261
262       my @hashrefs = (
263         { 'company'      => { op=>'ILIKE', value=>"%$value%" }, },
264         { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
265       );
266
267       if ( $first && $last ) {
268
269         push @hashrefs,
270           { 'first'        => { op=>'ILIKE', value=>"%$first%" },
271             'last'         => { op=>'ILIKE', value=>"%$last%" },
272           },
273           { 'ship_first'   => { op=>'ILIKE', value=>"%$first%" },
274             'ship_last'    => { op=>'ILIKE', value=>"%$last%" },
275           },
276         ;
277
278       } else {
279
280         push @hashrefs,
281           { 'last'         => { op=>'ILIKE', value=>"%$value%" }, },
282           { 'ship_last'    => { op=>'ILIKE', value=>"%$value%" }, },
283         ;
284       }
285
286       if ( $conf->exists('address1-search') ) {
287         push @hashrefs,
288           { 'address1'      => { op=>'ILIKE', value=>"%$value%" }, },
289           { 'ship_address1' => { op=>'ILIKE', value=>"%$value%" }, },
290         ;
291       }
292
293       foreach my $hashref ( @hashrefs ) {
294
295         push @cust_main, qsearch( {
296           'table'     => 'cust_main',
297           'hashref'   => { %$hashref,
298                            %options,
299                          },
300           'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
301         } );
302
303       }
304
305       #fuzzy
306       my @fuzopts = (
307         \%options,                #hashref
308         '',                       #select
309         " AND $agentnums_sql",    #extra_sql  #agent virtualization
310       );
311
312       if ( $first && $last ) {
313         push @cust_main, FS::cust_main::Search->fuzzy_search(
314           { 'last'   => $last,    #fuzzy hashref
315             'first'  => $first }, #
316           @fuzopts
317         );
318       }
319       foreach my $field ( 'last', 'company' ) {
320         push @cust_main,
321           FS::cust_main::Search->fuzzy_search( { $field => $value }, @fuzopts );
322       }
323       if ( $conf->exists('address1-search') ) {
324         push @cust_main,
325           FS::cust_main::Search->fuzzy_search( { 'address1' => $value }, @fuzopts );
326       }
327
328     }
329
330   }
331
332   #eliminate duplicates
333   my %saw = ();
334   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
335
336   @cust_main;
337
338 }
339
340 =item email_search
341
342 Accepts the following options: I<email>, the email address to search for.  The
343 email address will be searched for as an email invoice destination and as an
344 svc_acct account.
345
346 #Any additional options are treated as an additional qualifier on the search
347 #(i.e. I<agentnum>).
348
349 Returns a (possibly empty) array of FS::cust_main objects (but usually just
350 none or one).
351
352 =cut
353
354 sub email_search {
355   my %options = @_;
356
357   local($DEBUG) = 1;
358
359   my $email = delete $options{'email'};
360
361   #we're only being used by RT at the moment... no agent virtualization yet
362   #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
363
364   my @cust_main = ();
365
366   if ( $email =~ /([^@]+)\@([^@]+)/ ) {
367
368     my ( $user, $domain ) = ( $1, $2 );
369
370     warn "$me smart_search: searching for $user in domain $domain"
371       if $DEBUG;
372
373     push @cust_main,
374       map $_->cust_main,
375           qsearch( {
376                      'table'     => 'cust_main_invoice',
377                      'hashref'   => { 'dest' => $email },
378                    }
379                  );
380
381     push @cust_main,
382       map  $_->cust_main,
383       grep $_,
384       map  $_->cust_svc->cust_pkg,
385           qsearch( {
386                      'table'     => 'svc_acct',
387                      'hashref'   => { 'username' => $user, },
388                      'extra_sql' =>
389                        'AND ( SELECT domain FROM svc_domain
390                                 WHERE svc_acct.domsvc = svc_domain.svcnum
391                             ) = '. dbh->quote($domain),
392                    }
393                  );
394   }
395
396   my %saw = ();
397   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
398
399   warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
400     if $DEBUG;
401
402   @cust_main;
403
404 }
405
406 =back
407
408 =head1 CLASS METHODS
409
410 =over 4
411
412 =item search HASHREF
413
414 (Class method)
415
416 Returns a qsearch hash expression to search for parameters specified in
417 HASHREF.  Valid parameters are
418
419 =over 4
420
421 =item agentnum
422
423 =item status
424
425 =item cancelled_pkgs
426
427 bool
428
429 =item signupdate
430
431 listref of start date, end date
432
433 =item payby
434
435 listref
436
437 =item paydate_year
438
439 =item paydate_month
440
441 =item current_balance
442
443 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
444
445 =item cust_fields
446
447 =item flattened_pkgs
448
449 bool
450
451 =back
452
453 =cut
454
455 sub search {
456   my ($class, $params) = @_;
457
458   my $dbh = dbh;
459
460   my @where = ();
461   my $orderby;
462
463   ##
464   # parse agent
465   ##
466
467   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
468     push @where,
469       "cust_main.agentnum = $1";
470   }
471
472   ##
473   # do the same for user
474   ##
475
476   if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
477     push @where,
478       "cust_main.usernum = $1";
479   }
480
481   ##
482   # parse status
483   ##
484
485   #prospect ordered active inactive suspended cancelled
486   if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
487     my $method = $params->{'status'}. '_sql';
488     #push @where, $class->$method();
489     push @where, FS::cust_main->$method();
490   }
491   
492   ##
493   # parse cancelled package checkbox
494   ##
495
496   my $pkgwhere = "";
497
498   $pkgwhere .= "AND (cancel = 0 or cancel is null)"
499     unless $params->{'cancelled_pkgs'};
500
501   ##
502   # parse without census tract checkbox
503   ##
504
505   push @where, "(censustract = '' or censustract is null)"
506     if $params->{'no_censustract'};
507
508   ##
509   # dates
510   ##
511
512   foreach my $field (qw( signupdate )) {
513
514     next unless exists($params->{$field});
515
516     my($beginning, $ending, $hour) = @{$params->{$field}};
517
518     push @where,
519       "cust_main.$field IS NOT NULL",
520       "cust_main.$field >= $beginning",
521       "cust_main.$field <= $ending";
522
523     # XXX: do this for mysql and/or pull it out of here
524     if(defined $hour) {
525       if ($dbh->{Driver}->{Name} eq 'Pg') {
526         push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
527       }
528       else {
529         warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
530       }
531     }
532
533     $orderby ||= "ORDER BY cust_main.$field";
534
535   }
536
537   ###
538   # classnum
539   ###
540
541   if ( $params->{'classnum'} ) {
542
543     my @classnum = ref( $params->{'classnum'} )
544                      ? @{ $params->{'classnum'} }
545                      :  ( $params->{'classnum'} );
546
547     @classnum = grep /^(\d*)$/, @classnum;
548
549     if ( @classnum ) {
550       push @where, '( '. join(' OR ', map {
551                                             $_ ? "cust_main.classnum = $_"
552                                                : "cust_main.classnum IS NULL"
553                                           }
554                                           @classnum
555                              ).
556                    ' )';
557     }
558
559   }
560
561   ###
562   # payby
563   ###
564
565   if ( $params->{'payby'} ) {
566
567     my @payby = ref( $params->{'payby'} )
568                   ? @{ $params->{'payby'} }
569                   :  ( $params->{'payby'} );
570
571     @payby = grep /^([A-Z]{4})$/, @payby;
572
573     push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
574       if @payby;
575
576   }
577
578   ###
579   # paydate_year / paydate_month
580   ###
581
582   if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
583     my $year = $1;
584     $params->{'paydate_month'} =~ /^(\d\d?)$/
585       or die "paydate_year without paydate_month?";
586     my $month = $1;
587
588     push @where,
589       'paydate IS NOT NULL',
590       "paydate != ''",
591       "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
592 ;
593   }
594
595   ###
596   # invoice terms
597   ###
598
599   if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
600     my $terms = $1;
601     if ( $1 eq 'NULL' ) {
602       push @where,
603         "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
604     } else {
605       push @where,
606         "cust_main.invoice_terms IS NOT NULL",
607         "cust_main.invoice_terms = '$1'";
608     }
609   }
610
611   ##
612   # amounts
613   ##
614
615   if ( $params->{'current_balance'} ) {
616
617     #my $balance_sql = $class->balance_sql();
618     my $balance_sql = FS::cust_main->balance_sql();
619
620     my @current_balance =
621       ref( $params->{'current_balance'} )
622       ? @{ $params->{'current_balance'} }
623       :  ( $params->{'current_balance'} );
624
625     push @where, map { s/current_balance/$balance_sql/; $_ }
626                      @current_balance;
627
628   }
629
630   ##
631   # custbatch
632   ##
633
634   if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
635     push @where,
636       "cust_main.custbatch = '$1'";
637   }
638
639   ##
640   # setup queries, subs, etc. for the search
641   ##
642
643   $orderby ||= 'ORDER BY custnum';
644
645   # here is the agent virtualization
646   push @where, $FS::CurrentUser::CurrentUser->agentnums_sql;
647
648   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
649
650   my $addl_from = 'LEFT JOIN cust_pkg USING ( custnum  ) ';
651
652   my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
653
654   my $select = join(', ', 
655                  'cust_main.custnum',
656                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
657                );
658
659   my(@extra_headers) = ();
660   my(@extra_fields)  = ();
661
662   if ($params->{'flattened_pkgs'}) {
663
664     if ($dbh->{Driver}->{Name} eq 'Pg') {
665
666       $select .= ", array_to_string(array(select pkg from cust_pkg left join part_pkg using ( pkgpart ) where cust_main.custnum = cust_pkg.custnum $pkgwhere),'|') as magic";
667
668     }elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
669       $select .= ", GROUP_CONCAT(pkg SEPARATOR '|') as magic";
670       $addl_from .= " LEFT JOIN part_pkg using ( pkgpart )";
671     }else{
672       warn "warning: unknown database type ". $dbh->{Driver}->{Name}. 
673            "omitting packing information from report.";
674     }
675
676     my $header_query = "SELECT COUNT(cust_pkg.custnum = cust_main.custnum) AS count FROM cust_main $addl_from $extra_sql $pkgwhere group by cust_main.custnum order by count desc limit 1";
677
678     my $sth = dbh->prepare($header_query) or die dbh->errstr;
679     $sth->execute() or die $sth->errstr;
680     my $headerrow = $sth->fetchrow_arrayref;
681     my $headercount = $headerrow ? $headerrow->[0] : 0;
682     while($headercount) {
683       unshift @extra_headers, "Package ". $headercount;
684       unshift @extra_fields, eval q!sub {my $c = shift;
685                                          my @a = split '\|', $c->magic;
686                                          my $p = $a[!.--$headercount. q!];
687                                          $p;
688                                         };!;
689     }
690
691   }
692
693   my $sql_query = {
694     'table'         => 'cust_main',
695     'select'        => $select,
696     'hashref'       => {},
697     'extra_sql'     => $extra_sql,
698     'order_by'      => $orderby,
699     'count_query'   => $count_query,
700     'extra_headers' => \@extra_headers,
701     'extra_fields'  => \@extra_fields,
702   };
703
704 }
705
706 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
707
708 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
709 records.  Currently, I<first>, I<last>, I<company> and/or I<address1> may be
710 specified (the appropriate ship_ field is also searched).
711
712 Additional options are the same as FS::Record::qsearch
713
714 =cut
715
716 sub fuzzy_search {
717   my( $self, $fuzzy, $hash, @opt) = @_;
718   #$self
719   $hash ||= {};
720   my @cust_main = ();
721
722   check_and_rebuild_fuzzyfiles();
723   foreach my $field ( keys %$fuzzy ) {
724
725     my $all = $self->all_X($field);
726     next unless scalar(@$all);
727
728     my %match = ();
729     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
730
731     my @fcust = ();
732     foreach ( keys %match ) {
733       push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
734       push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
735     }
736     my %fsaw = ();
737     push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
738   }
739
740   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
741   my %saw = ();
742   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
743
744   @cust_main;
745
746 }
747
748 =back
749
750 =head1 UTILITY SUBROUTINES
751
752 =over 4
753
754 =item check_and_rebuild_fuzzyfiles
755
756 =cut
757
758 sub check_and_rebuild_fuzzyfiles {
759   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
760   rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields
761 }
762
763 =item rebuild_fuzzyfiles
764
765 =cut
766
767 sub rebuild_fuzzyfiles {
768
769   use Fcntl qw(:flock);
770
771   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
772   mkdir $dir, 0700 unless -d $dir;
773
774   foreach my $fuzzy ( @fuzzyfields ) {
775
776     open(LOCK,">>$dir/cust_main.$fuzzy")
777       or die "can't open $dir/cust_main.$fuzzy: $!";
778     flock(LOCK,LOCK_EX)
779       or die "can't lock $dir/cust_main.$fuzzy: $!";
780
781     open (CACHE,">$dir/cust_main.$fuzzy.tmp")
782       or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
783
784     foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
785       my $sth = dbh->prepare("SELECT $field FROM cust_main".
786                              " WHERE $field != '' AND $field IS NOT NULL");
787       $sth->execute or die $sth->errstr;
788
789       while ( my $row = $sth->fetchrow_arrayref ) {
790         print CACHE $row->[0]. "\n";
791       }
792
793     } 
794
795     close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
796   
797     rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
798     close LOCK;
799   }
800
801 }
802
803 =item all_X
804
805 =cut
806
807 sub all_X {
808   my( $self, $field ) = @_;
809   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
810   open(CACHE,"<$dir/cust_main.$field")
811     or die "can't open $dir/cust_main.$field: $!";
812   my @array = map { chomp; $_; } <CACHE>;
813   close CACHE;
814   \@array;
815 }
816
817 =head1 BUGS
818
819 Bed bugs
820
821 =head1 SEE ALSO
822
823 L<FS::cust_main>, L<FS::Record>
824
825 =cut
826
827 1;
828