fix "add package columns" in customer report, RT#22525
[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 = ( 'first', 'last', 'company', 'address1' );
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 = 
68     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
69
70   my @cust_main = ();
71
72   my $skip_fuzzy = delete $options{'no_fuzzy_on_exact'};
73   my $search = delete $options{'search'};
74   ( my $alphanum_search = $search ) =~ s/\W//g;
75   
76   if ( $alphanum_search =~ /^1?(\d{3})(\d{3})(\d{4})(\d*)$/ ) { #phone# search
77
78     #false laziness w/Record::ut_phone
79     my $phonen = "$1-$2-$3";
80     $phonen .= " x$4" if $4;
81
82     push @cust_main, qsearch( {
83       'table'   => 'cust_main',
84       'hashref' => { %options },
85       'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
86                      ' ( '.
87                          join(' OR ', map "$_ = '$phonen'",
88                                           qw( daytime night mobile fax
89                                               ship_daytime ship_night ship_mobile ship_fax )
90                              ).
91                      ' ) '.
92                      " AND $agentnums_sql", #agent virtualization
93     } );
94
95     unless ( @cust_main || $phonen =~ /x\d+$/ ) { #no exact match
96       #try looking for matches with extensions unless one was specified
97
98       push @cust_main, qsearch( {
99         'table'   => 'cust_main',
100         'hashref' => { %options },
101         'extra_sql' => ( scalar(keys %options) ? ' AND ' : ' WHERE ' ).
102                        ' ( '.
103                            join(' OR ', map "$_ LIKE '$phonen\%'",
104                                             qw( daytime night
105                                                 ship_daytime ship_night )
106                                ).
107                        ' ) '.
108                        " AND $agentnums_sql", #agent virtualization
109       } );
110
111     }
112
113   # custnum search (also try agent_custid), with some tweaking options if your
114   # legacy cust "numbers" have letters
115   } 
116   
117   
118   if ( $search =~ /@/ ) {
119       push @cust_main,
120           map $_->cust_main,
121               qsearch( {
122                          'table'     => 'cust_main_invoice',
123                          'hashref'   => { 'dest' => $search },
124                        }
125                      );
126   } elsif ( $search =~ /^\s*(\d+)\s*$/
127          || ( $conf->config('cust_main-agent_custid-format') eq 'ww?d+'
128               && $search =~ /^\s*(\w\w?\d+)\s*$/
129             )
130          || ( $conf->config('cust_main-custnum-display_special')
131            # it's not currently possible for special prefixes to contain
132            # digits, so just strip off any alphabetic prefix and match 
133            # the rest to custnum
134               && $search =~ /^\s*[[:alpha:]]*(\d+)\s*$/
135             )
136          || ( $conf->exists('address1-search' )
137               && $search =~ /^\s*(\d+\-?\w*)\s*$/ #i.e. 1234A or 9432-D
138             )
139      )
140   {
141
142     my $num = $1;
143
144     if ( $num =~ /^(\d+)$/ && $num <= 2147483647 ) { #need a bigint custnum? wow
145       my $agent_custid_null = $conf->exists('cust_main-default_agent_custid')
146                                 ? ' AND agent_custid IS NULL ' : '';
147       push @cust_main, qsearch( {
148         'table'     => 'cust_main',
149         'hashref'   => { 'custnum' => $num, %options },
150         'extra_sql' => " AND $agentnums_sql $agent_custid_null",
151       } );
152     }
153
154     # for all agents this user can see, if any of them have custnum prefixes 
155     # that match the search string, include customers that match the rest 
156     # of the custnum and belong to that agent
157     foreach my $agentnum ( $FS::CurrentUser::CurrentUser->agentnums ) {
158       my $p = $conf->config('cust_main-custnum-display_prefix', $agentnum);
159       next if !$p;
160       if ( $p eq substr($num, 0, length($p)) ) {
161         push @cust_main, qsearch( {
162           'table'   => 'cust_main',
163           'hashref' => { 'custnum' => 0 + substr($num, length($p)),
164                          'agentnum' => $agentnum,
165                           %options,
166                        },
167         } );
168       }
169     }
170
171     push @cust_main, qsearch( {
172         'table'     => 'cust_main',
173         'hashref'   => { 'agent_custid' => $num, %options },
174         'extra_sql' => " AND $agentnums_sql", #agent virtualization
175     } );
176
177     if ( $conf->exists('address1-search') ) {
178       my $len = length($num);
179       $num = lc($num);
180       foreach my $prefix ( '', 'ship_' ) {
181         push @cust_main, qsearch( {
182           'table'     => 'cust_main',
183           'hashref'   => { %options, },
184           'extra_sql' => 
185             ( keys(%options) ? ' AND ' : ' WHERE ' ).
186             " LOWER(SUBSTRING(${prefix}address1 FROM 1 FOR $len)) = '$num' ".
187             " AND $agentnums_sql",
188         } );
189       }
190     }
191
192   } elsif ( $search =~ /^\s*(\S.*\S)\s+\((.+), ([^,]+)\)\s*$/ ) {
193
194     my($company, $last, $first) = ( $1, $2, $3 );
195
196     # "Company (Last, First)"
197     #this is probably something a browser remembered,
198     #so just do an exact search (but case-insensitive, so USPS standardization
199     #doesn't throw a wrench in the works)
200
201     foreach my $prefix ( '', 'ship_' ) {
202       push @cust_main, qsearch( {
203         'table'     => 'cust_main',
204         'hashref'   => { %options },
205         'extra_sql' => 
206           ( keys(%options) ? ' AND ' : ' WHERE ' ).
207           join(' AND ',
208             " LOWER(${prefix}first)   = ". dbh->quote(lc($first)),
209             " LOWER(${prefix}last)    = ". dbh->quote(lc($last)),
210             " LOWER(${prefix}company) = ". dbh->quote(lc($company)),
211             $agentnums_sql,
212           ),
213       } );
214     }
215
216   } elsif ( $search =~ /^\s*(\S.*\S)\s*$/ ) { # value search
217                                               # try (ship_){last,company}
218
219     my $value = lc($1);
220
221     # # remove "(Last, First)" in "Company (Last, First)", otherwise the
222     # # full strings the browser remembers won't work
223     # $value =~ s/\([\w \,\.\-\']*\)$//; #false laziness w/Record::ut_name
224
225     use Lingua::EN::NameParse;
226     my $NameParse = new Lingua::EN::NameParse(
227              auto_clean     => 1,
228              allow_reversed => 1,
229     );
230
231     my($last, $first) = ( '', '' );
232     #maybe disable this too and just rely on NameParse?
233     if ( $value =~ /^(.+),\s*([^,]+)$/ ) { # Last, First
234     
235       ($last, $first) = ( $1, $2 );
236     
237     #} elsif  ( $value =~ /^(.+)\s+(.+)$/ ) {
238     } elsif ( ! $NameParse->parse($value) ) {
239
240       my %name = $NameParse->components;
241       $first = $name{'given_name_1'} || $name{'initials_1'}; #wtf NameParse, Ed?
242       $last  = $name{'surname_1'};
243
244     }
245
246     if ( $first && $last ) {
247
248       my($q_last, $q_first) = ( dbh->quote($last), dbh->quote($first) );
249
250       #exact
251       my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
252       $sql .= "
253         (     ( LOWER(last) = $q_last AND LOWER(first) = $q_first )
254            OR ( LOWER(ship_last) = $q_last AND LOWER(ship_first) = $q_first )
255         )";
256
257       push @cust_main, qsearch( {
258         'table'     => 'cust_main',
259         'hashref'   => \%options,
260         'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
261       } );
262
263       # or it just be something that was typed in... (try that in a sec)
264
265     }
266
267     my $q_value = dbh->quote($value);
268
269     #exact
270     my $sql = scalar(keys %options) ? ' AND ' : ' WHERE ';
271     $sql .= " (    LOWER(last)          = $q_value
272                 OR LOWER(company)       = $q_value
273                 OR LOWER(ship_last)     = $q_value
274                 OR LOWER(ship_company)  = $q_value
275             ";
276     $sql .= "   OR LOWER(address1)      = $q_value
277                 OR LOWER(ship_address1) = $q_value
278             "
279       if $conf->exists('address1-search');
280     $sql .= " )";
281
282     push @cust_main, qsearch( {
283       'table'     => 'cust_main',
284       'hashref'   => \%options,
285       'extra_sql' => "$sql AND $agentnums_sql", #agent virtualization
286     } );
287
288     #no exact match, trying substring/fuzzy
289     #always do substring & fuzzy (unless they're explicity config'ed off)
290     #getting complaints searches are not returning enough
291     unless ( @cust_main  && $skip_fuzzy || $conf->exists('disable-fuzzy') ) {
292
293       #still some false laziness w/search (was search/cust_main.cgi)
294
295       #substring
296
297       my @hashrefs = (
298         { 'company'      => { op=>'ILIKE', value=>"%$value%" }, },
299         { 'ship_company' => { op=>'ILIKE', value=>"%$value%" }, },
300       );
301
302       if ( $first && $last ) {
303
304         push @hashrefs,
305           { 'first'        => { op=>'ILIKE', value=>"%$first%" },
306             'last'         => { op=>'ILIKE', value=>"%$last%" },
307           },
308           { 'ship_first'   => { op=>'ILIKE', value=>"%$first%" },
309             'ship_last'    => { op=>'ILIKE', value=>"%$last%" },
310           },
311         ;
312
313       } else {
314
315         push @hashrefs,
316           { 'last'         => { op=>'ILIKE', value=>"%$value%" }, },
317           { 'ship_last'    => { op=>'ILIKE', value=>"%$value%" }, },
318         ;
319       }
320
321       if ( $conf->exists('address1-search') ) {
322         push @hashrefs,
323           { 'address1'      => { op=>'ILIKE', value=>"%$value%" }, },
324           { 'ship_address1' => { op=>'ILIKE', value=>"%$value%" }, },
325         ;
326       }
327
328       foreach my $hashref ( @hashrefs ) {
329
330         push @cust_main, qsearch( {
331           'table'     => 'cust_main',
332           'hashref'   => { %$hashref,
333                            %options,
334                          },
335           'extra_sql' => " AND $agentnums_sql", #agent virtualizaiton
336         } );
337
338       }
339
340       #fuzzy
341       my @fuzopts = (
342         \%options,                #hashref
343         '',                       #select
344         " AND $agentnums_sql",    #extra_sql  #agent virtualization
345       );
346
347       if ( $first && $last ) {
348         push @cust_main, FS::cust_main::Search->fuzzy_search(
349           { 'last'   => $last,    #fuzzy hashref
350             'first'  => $first }, #
351           @fuzopts
352         );
353       }
354       foreach my $field ( 'last', 'company' ) {
355         push @cust_main,
356           FS::cust_main::Search->fuzzy_search( { $field => $value }, @fuzopts );
357       }
358       if ( $conf->exists('address1-search') ) {
359         push @cust_main,
360           FS::cust_main::Search->fuzzy_search( { 'address1' => $value }, @fuzopts );
361       }
362
363     }
364
365   }
366
367   #eliminate duplicates
368   my %saw = ();
369   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
370
371   @cust_main;
372
373 }
374
375 =item email_search
376
377 Accepts the following options: I<email>, the email address to search for.  The
378 email address will be searched for as an email invoice destination and as an
379 svc_acct account.
380
381 #Any additional options are treated as an additional qualifier on the search
382 #(i.e. I<agentnum>).
383
384 Returns a (possibly empty) array of FS::cust_main objects (but usually just
385 none or one).
386
387 =cut
388
389 sub email_search {
390   my %options = @_;
391
392   local($DEBUG) = 1;
393
394   my $email = delete $options{'email'};
395
396   #we're only being used by RT at the moment... no agent virtualization yet
397   #my $agentnums_sql = $FS::CurrentUser::CurrentUser->agentnums_sql;
398
399   my @cust_main = ();
400
401   if ( $email =~ /([^@]+)\@([^@]+)/ ) {
402
403     my ( $user, $domain ) = ( $1, $2 );
404
405     warn "$me smart_search: searching for $user in domain $domain"
406       if $DEBUG;
407
408     push @cust_main,
409       map $_->cust_main,
410           qsearch( {
411                      'table'     => 'cust_main_invoice',
412                      'hashref'   => { 'dest' => $email },
413                    }
414                  );
415
416     push @cust_main,
417       map  $_->cust_main,
418       grep $_,
419       map  $_->cust_svc->cust_pkg,
420           qsearch( {
421                      'table'     => 'svc_acct',
422                      'hashref'   => { 'username' => $user, },
423                      'extra_sql' =>
424                        'AND ( SELECT domain FROM svc_domain
425                                 WHERE svc_acct.domsvc = svc_domain.svcnum
426                             ) = '. dbh->quote($domain),
427                    }
428                  );
429   }
430
431   my %saw = ();
432   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
433
434   warn "$me smart_search: found ". scalar(@cust_main). " unique customers"
435     if $DEBUG;
436
437   @cust_main;
438
439 }
440
441 =back
442
443 =head1 CLASS METHODS
444
445 =over 4
446
447 =item search HASHREF
448
449 (Class method)
450
451 Returns a qsearch hash expression to search for parameters specified in
452 HASHREF.  Valid parameters are
453
454 =over 4
455
456 =item agentnum
457
458 =item status
459
460 =item address
461
462 =item refnum
463
464 =item cancelled_pkgs
465
466 bool
467
468 =item signupdate
469
470 listref of start date, end date
471
472 =item birthdate
473
474 listref of start date, end date
475
476 =item spouse_birthdate
477
478 listref of start date, end date
479
480 =item anniversary_date
481
482 listref of start date, end date
483
484 =item payby
485
486 listref
487
488 =item paydate_year
489
490 =item paydate_month
491
492 =item current_balance
493
494 listref (list returned by FS::UI::Web::parse_lt_gt($cgi, 'current_balance'))
495
496 =item cust_fields
497
498 =item flattened_pkgs
499
500 bool
501
502 =back
503
504 =cut
505
506 sub search {
507   my ($class, $params) = @_;
508
509   my $dbh = dbh;
510
511   my @where = ();
512   my $orderby;
513
514   # initialize these to prevent warnings
515   $params = {
516     'custnum'       => '',
517     'agentnum'      => '',
518     'usernum'       => '',
519     'status'        => '',
520     'address'       => '',
521     'paydate_year'  => '',
522     'invoice_terms' => '',
523     'custbatch'     => '',
524     %$params
525   };
526
527   ##
528   # explicit custnum(s)
529   ##
530
531   if ( $params->{'custnum'} ) {
532     my @custnums = ref($params->{'custnum'}) ? 
533                       @{ $params->{'custnum'} } : 
534                       $params->{'custnum'};
535     push @where, 
536       'cust_main.custnum IN (' . 
537       join(',', map { $_ =~ /^(\d+)$/ ? $1 : () } @custnums ) .
538       ')' if scalar(@custnums) > 0;
539   }
540
541   ##
542   # parse agent
543   ##
544
545   if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
546     push @where,
547       "cust_main.agentnum = $1";
548   }
549
550   ##
551   # do the same for user
552   ##
553
554   if ( $params->{'usernum'} =~ /^(\d+)$/ and $1 ) {
555     push @where,
556       "cust_main.usernum = $1";
557   }
558
559   ##
560   # parse status
561   ##
562
563   #prospect ordered active inactive suspended cancelled
564   if ( grep { $params->{'status'} eq $_ } FS::cust_main->statuses() ) {
565     my $method = $params->{'status'}. '_sql';
566     #push @where, $class->$method();
567     push @where, FS::cust_main->$method();
568   }
569
570   ##
571   # address
572   ##
573   if ( $params->{'address'} =~ /\S/ ) {
574     my $address = dbh->quote('%'. lc($params->{'address'}). '%');
575     push @where, '('. join(' OR ',
576                              map "LOWER($_) LIKE $address",
577                                qw(address1 address2 ship_address1 ship_address2)
578                           ).
579                  ')';
580   }
581
582   ###
583   # refnum
584   ###
585   if ( $params->{'refnum'}  ) {
586
587     my @refnum = ref( $params->{'refnum'} )
588                    ? @{ $params->{'refnum'} }
589                    :  ( $params->{'refnum'} );
590
591     @refnum = grep /^(\d*)$/, @refnum;
592
593     push @where, '( '. join(' OR ', map "cust_main.refnum = $_", @refnum ). ' )'
594       if @refnum;
595
596   }
597
598   ##
599   # parse cancelled package checkbox
600   ##
601
602   my $pkgwhere = "";
603
604   $pkgwhere .= "AND (cancel = 0 or cancel is null)"
605     unless $params->{'cancelled_pkgs'};
606
607   ##
608   # parse without census tract checkbox
609   ##
610
611   push @where, "(censustract = '' or censustract is null)"
612     if $params->{'no_censustract'};
613
614   ##
615   # parse with hardcoded tax location checkbox
616   ##
617
618   push @where, "geocode is not null"
619     if $params->{'with_geocode'};
620
621   ##
622   # "with email address(es)" checkbox
623   ##
624
625   push @where,
626     'EXISTS ( SELECT 1 FROM cust_main_invoice
627                 WHERE cust_main_invoice.custnum = cust_main.custnum
628                   AND length(dest) > 5
629             )'  # AND dest LIKE '%@%'
630     if $params->{'with_email'};
631
632   ##
633   # "without postal mail invoices" checkbox
634   ##
635
636   push @where,
637     "NOT EXISTS ( SELECT 1 FROM cust_main_invoice
638                     WHERE cust_main_invoice.custnum = cust_main.custnum
639                       AND dest = 'POST' )"
640     if $params->{'no_POST'};
641
642   ##
643   # dates
644   ##
645
646   foreach my $field (qw( signupdate birthdate spouse_birthdate anniversary_date )) {
647
648     next unless exists($params->{$field});
649
650     my($beginning, $ending, $hour) = @{$params->{$field}};
651
652     push @where,
653       "cust_main.$field IS NOT NULL",
654       "cust_main.$field >= $beginning",
655       "cust_main.$field <= $ending";
656
657     if($field eq 'signupdate' && defined $hour) {
658       if ($dbh->{Driver}->{Name} =~ /Pg/i) {
659         push @where, "extract(hour from to_timestamp(cust_main.$field)) = $hour";
660       }
661       elsif( $dbh->{Driver}->{Name} =~ /mysql/i) {
662         push @where, "hour(from_unixtime(cust_main.$field)) = $hour"
663       }
664       else {
665         warn "search by time of day not supported on ".$dbh->{Driver}->{Name}." databases";
666       }
667     }
668
669     $orderby ||= "ORDER BY cust_main.$field";
670
671   }
672
673   ###
674   # classnum
675   ###
676
677   if ( $params->{'classnum'} ) {
678
679     my @classnum = ref( $params->{'classnum'} )
680                      ? @{ $params->{'classnum'} }
681                      :  ( $params->{'classnum'} );
682
683     @classnum = grep /^(\d*)$/, @classnum;
684
685     if ( @classnum ) {
686       push @where, '( '. join(' OR ', map {
687                                             $_ ? "cust_main.classnum = $_"
688                                                : "cust_main.classnum IS NULL"
689                                           }
690                                           @classnum
691                              ).
692                    ' )';
693     }
694
695   }
696
697   ###
698   # payby
699   ###
700
701   if ( $params->{'payby'} ) {
702
703     my @payby = ref( $params->{'payby'} )
704                   ? @{ $params->{'payby'} }
705                   :  ( $params->{'payby'} );
706
707     @payby = grep /^([A-Z]{4})$/, @payby;
708
709     push @where, '( '. join(' OR ', map "cust_main.payby = '$_'", @payby). ' )'
710       if @payby;
711
712   }
713
714   ###
715   # paydate_year / paydate_month
716   ###
717
718   if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
719     my $year = $1;
720     $params->{'paydate_month'} =~ /^(\d\d?)$/
721       or die "paydate_year without paydate_month?";
722     my $month = $1;
723
724     push @where,
725       'paydate IS NOT NULL',
726       "paydate != ''",
727       "CAST(paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
728 ;
729   }
730
731   ###
732   # invoice terms
733   ###
734
735   if ( $params->{'invoice_terms'} =~ /^([\w ]+)$/ ) {
736     my $terms = $1;
737     if ( $1 eq 'NULL' ) {
738       push @where,
739         "( cust_main.invoice_terms IS NULL OR cust_main.invoice_terms = '' )";
740     } else {
741       push @where,
742         "cust_main.invoice_terms IS NOT NULL",
743         "cust_main.invoice_terms = '$1'";
744     }
745   }
746
747   ##
748   # amounts
749   ##
750
751   if ( $params->{'current_balance'} ) {
752
753     #my $balance_sql = $class->balance_sql();
754     my $balance_sql = FS::cust_main->balance_sql();
755
756     my @current_balance =
757       ref( $params->{'current_balance'} )
758       ? @{ $params->{'current_balance'} }
759       :  ( $params->{'current_balance'} );
760
761     push @where, map { s/current_balance/$balance_sql/; $_ }
762                      @current_balance;
763
764   }
765
766   ##
767   # custbatch
768   ##
769
770   if ( $params->{'custbatch'} =~ /^([\w\/\-\:\.]+)$/ and $1 ) {
771     push @where,
772       "cust_main.custbatch = '$1'";
773   }
774   
775   if ( $params->{'tagnum'} ) {
776     my @tagnums = ref( $params->{'tagnum'} ) ? @{ $params->{'tagnum'} } : ( $params->{'tagnum'} );
777
778     @tagnums = grep /^(\d+)$/, @tagnums;
779
780     if ( @tagnums ) {
781         my $tags_where = "0 < (select count(1) from cust_tag where " 
782                 . " cust_tag.custnum = cust_main.custnum and tagnum in ("
783                 . join(',', @tagnums) . "))";
784
785         push @where, $tags_where;
786     }
787   }
788
789
790   ##
791   # setup queries, subs, etc. for the search
792   ##
793
794   $orderby ||= 'ORDER BY custnum';
795
796   # here is the agent virtualization
797   push @where,
798     $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
799
800   my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
801
802   my $addl_from = '';
803
804   my $count_query = "SELECT COUNT(*) FROM cust_main $extra_sql";
805
806   my @select = (
807                  'cust_main.custnum',
808                  FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
809                );
810
811   my(@extra_headers) = ();
812   my(@extra_fields)  = ();
813
814   if ($params->{'flattened_pkgs'}) {
815
816     #my $pkg_join = '';
817     $addl_from .=
818       ' LEFT JOIN cust_pkg ON ( cust_main.custnum = cust_pkg.custnum ) ';
819
820     if ($dbh->{Driver}->{Name} eq 'Pg') {
821
822       push @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";
823
824     } elsif ($dbh->{Driver}->{Name} =~ /^mysql/i) {
825       push @select, "GROUP_CONCAT(part_pkg.pkg SEPARATOR '|') as magic";
826       $addl_from .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
827       #$pkg_join  .= ' LEFT JOIN part_pkg USING ( pkgpart ) ';
828     } else {
829       warn "warning: unknown database type ". $dbh->{Driver}->{Name}. 
830            "omitting package information from report.";
831     }
832
833     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";
834
835     my $sth = dbh->prepare($header_query) or die dbh->errstr;
836     $sth->execute() or die $sth->errstr;
837     my $headerrow = $sth->fetchrow_arrayref;
838     my $headercount = $headerrow ? $headerrow->[0] : 0;
839     while($headercount) {
840       unshift @extra_headers, "Package ". $headercount;
841       unshift @extra_fields, eval q!sub {my $c = shift;
842                                          my @a = split '\|', $c->magic;
843                                          my $p = $a[!.--$headercount. q!];
844                                          $p;
845                                         };!;
846     }
847
848   }
849
850   if ( $params->{'with_geocode'} ) {
851
852     unshift @extra_headers, 'Tax location override', 'Calculated tax location';
853     unshift @extra_fields, sub { my $c = shift; $c->get('geocode'); },
854                            sub { my $c = shift;
855                                  $c->set('geocode', '');
856                                  $c->geocode('cch'); #XXX only cch right now
857                                };
858     push @select, 'geocode';
859     push @select, 'zip' unless grep { $_ eq 'zip' } @select;
860     push @select, 'ship_zip' unless grep { $_ eq 'ship_zip' } @select;
861   }
862
863   my $select = join(', ', @select);
864
865   my $sql_query = {
866     'table'         => 'cust_main',
867     'select'        => $select,
868     'addl_from'     => $addl_from,
869     'hashref'       => {},
870     'extra_sql'     => $extra_sql,
871     'order_by'      => $orderby,
872     'count_query'   => $count_query,
873     'extra_headers' => \@extra_headers,
874     'extra_fields'  => \@extra_fields,
875   };
876
877 }
878
879 =item fuzzy_search FUZZY_HASHREF [ HASHREF, SELECT, EXTRA_SQL, CACHE_OBJ ]
880
881 Performs a fuzzy (approximate) search and returns the matching FS::cust_main
882 records.  Currently, I<first>, I<last>, I<company> and/or I<address1> may be
883 specified (the appropriate ship_ field is also searched).
884
885 Additional options are the same as FS::Record::qsearch
886
887 =cut
888
889 sub fuzzy_search {
890   my( $self, $fuzzy, $hash, @opt) = @_;
891   #$self
892   $hash ||= {};
893   my @cust_main = ();
894
895   check_and_rebuild_fuzzyfiles();
896   foreach my $field ( keys %$fuzzy ) {
897
898     my $all = $self->all_X($field);
899     next unless scalar(@$all);
900
901     my %match = ();
902     $match{$_}=1 foreach ( amatch( $fuzzy->{$field}, ['i'], @$all ) );
903
904     my @fcust = ();
905     foreach ( keys %match ) {
906       push @fcust, qsearch('cust_main', { %$hash, $field=>$_}, @opt);
907       push @fcust, qsearch('cust_main', { %$hash, "ship_$field"=>$_}, @opt);
908     }
909     my %fsaw = ();
910     push @cust_main, grep { ! $fsaw{$_->custnum}++ } @fcust;
911   }
912
913   # we want the components of $fuzzy ANDed, not ORed, but still don't want dupes
914   my %saw = ();
915   @cust_main = grep { ++$saw{$_->custnum} == scalar(keys %$fuzzy) } @cust_main;
916
917   @cust_main;
918
919 }
920
921 =back
922
923 =head1 UTILITY SUBROUTINES
924
925 =over 4
926
927 =item check_and_rebuild_fuzzyfiles
928
929 =cut
930
931 sub check_and_rebuild_fuzzyfiles {
932   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
933   rebuild_fuzzyfiles() if grep { ! -e "$dir/cust_main.$_" } @fuzzyfields;
934 }
935
936 =item rebuild_fuzzyfiles
937
938 =cut
939
940 sub rebuild_fuzzyfiles {
941
942   use Fcntl qw(:flock);
943
944   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
945   mkdir $dir, 0700 unless -d $dir;
946
947   foreach my $fuzzy ( @fuzzyfields ) {
948
949     open(LOCK,">>$dir/cust_main.$fuzzy")
950       or die "can't open $dir/cust_main.$fuzzy: $!";
951     flock(LOCK,LOCK_EX)
952       or die "can't lock $dir/cust_main.$fuzzy: $!";
953
954     open (CACHE, '>:encoding(UTF-8)', "$dir/cust_main.$fuzzy.tmp")
955       or die "can't open $dir/cust_main.$fuzzy.tmp: $!";
956
957     foreach my $field ( $fuzzy, "ship_$fuzzy" ) {
958       my $sth = dbh->prepare("SELECT $field FROM cust_main".
959                              " WHERE $field != '' AND $field IS NOT NULL");
960       $sth->execute or die $sth->errstr;
961
962       while ( my $row = $sth->fetchrow_arrayref ) {
963         print CACHE $row->[0]. "\n";
964       }
965
966     } 
967
968     close CACHE or die "can't close $dir/cust_main.$fuzzy.tmp: $!";
969   
970     rename "$dir/cust_main.$fuzzy.tmp", "$dir/cust_main.$fuzzy";
971     close LOCK;
972   }
973
974 }
975
976 =item append_fuzzyfiles FIRSTNAME LASTNAME COMPANY ADDRESS1
977
978 =cut
979
980 sub append_fuzzyfiles {
981   #my( $first, $last, $company ) = @_;
982
983   check_and_rebuild_fuzzyfiles();
984
985   use Fcntl qw(:flock);
986
987   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
988
989   foreach my $field (@fuzzyfields) {
990     my $value = shift;
991
992     if ( $value ) {
993
994       open(CACHE, '>>:encoding(UTF-8)', "$dir/cust_main.$field" )
995         or die "can't open $dir/cust_main.$field: $!";
996       flock(CACHE,LOCK_EX)
997         or die "can't lock $dir/cust_main.$field: $!";
998
999       print CACHE "$value\n";
1000
1001       flock(CACHE,LOCK_UN)
1002         or die "can't unlock $dir/cust_main.$field: $!";
1003       close CACHE;
1004     }
1005
1006   }
1007
1008   1;
1009 }
1010
1011 =item all_X
1012
1013 =cut
1014
1015 sub all_X {
1016   my( $self, $field ) = @_;
1017   my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
1018   open(CACHE, '<:encoding(UTF-8)', "$dir/cust_main.$field")
1019     or die "can't open $dir/cust_main.$field: $!";
1020   my @array = map { chomp; $_; } <CACHE>;
1021   close CACHE;
1022   \@array;
1023 }
1024
1025 =head1 BUGS
1026
1027 Bed bugs
1028
1029 =head1 SEE ALSO
1030
1031 L<FS::cust_main>, L<FS::Record>
1032
1033 =cut
1034
1035 1;
1036