fix customer search, RT#40212, RT#40205, fallout from RT#20173
[freeside.git] / httemplate / search / cust_main.cgi
1 % if ( scalar(@cust_main) == 1 && ! $cgi->param('referral_custnum') ) {
2 %  if ( $cgi->param('quickpay') eq 'yes' ) {
3     <% $cgi->redirect(popurl(2). "edit/cust_pay.cgi?quickpay=yes;custnum=". $cust_main[0]->custnum) %>
4 %  } else {
5     <% $cgi->redirect(popurl(2). "view/cust_main.cgi?". $cust_main[0]->custnum) %>
6 %  }
7 %} elsif ( scalar(@cust_main) == 0 ) {
8 %  errorpage(emt("No matching customers found!"));
9 % } # errorpage quits, so we don't need an 'else' below
10
11 <& /elements/header.html, mt("Customer Search Results"), '' &>
12 % $total ||= scalar(@cust_main); 
13
14 <% mt("[_1] matching customers found",$total) |h %>
15
16 % my $pager = include( '/elements/pager.html',
17 %                        'offset'     => $offset,
18 %            'num_rows'   => scalar(@cust_main),
19 %            'total'      => $total,
20 %            'maxrecords' => $maxrecords,
21 %                    );
22
23 %  unless ( $cgi->param('cancelled') ) {
24 %    my $linklabel = '';
25 %    if ( $cgi->param('showcancelledcustomers') eq '0' #see if it was set by me
26 %         || ( $conf->exists('hidecancelledcustomers')
27 %              && ! $cgi->param('showcancelledcustomers')
28 %            )
29 %       ) {
30 %      $cgi->param('showcancelledcustomers', 1);
31 %      $linklabel = 'show';
32 %    } else {
33 %      $cgi->param('showcancelledcustomers', 0);
34 %      $linklabel = 'hide';
35 %    }
36 %    $cgi->param('offset', 0);
37         ( <a href="<% $cgi->self_url %>"><% mt("$linklabel canceled customers") |h %></a> )
38 %  }
39
40 %  if ( $cgi->param('referral_custnum') ) {
41 %    $cgi->param('referral_custnum') =~ /^(\d+)$/
42 %      or errorpage(emt("Illegal referral_custnum"));
43 %    my $referral_custnum = $1;
44 %    my $cust_main = qsearchs('cust_main', { custnum => $referral_custnum } );
45     <SCRIPT>
46         function changed(what) {
47             what.form.submit();
48         }
49     </SCRIPT>
50
51 % # XXX: translate this section...hard due to "referrals of CUST SELECT levels deep" construction
52     <FORM METHOD="GET">
53         <INPUT TYPE="hidden" NAME="referral_custnum" VALUE="<% $referral_custnum %>">
54 %   my $refcustlabel = "$referral_custnum: " .
55 %         ( $cust_main->company || $cust_main->last. ', '. $cust_main->first );
56         referrals of
57         <A HREF="<% popurl(2)."view/cust_main.cgi?$referral_custnum" %>"><% $refcustlabel |h %></A>
58         <SELECT NAME="referral_depth" SIZE="1" onChange="changed(this)">';
59
60 %    my $max = 8;
61 %    $cgi->param('referral_depth') =~ /^(\d*)$/ 
62 %      or errorpage(emt("Illegal referral_depth"));
63 %    my $referral_depth = $1;
64
65 %    foreach my $depth ( 1 .. $max ) {
66 %       my $selected = ($depth == $referral_depth) ? 'SELECTED' : '';
67         <OPTION <% $selected %>><% $depth %>
68 %    }
69     </SELECT> levels deep
70     </FORM>
71 %  }
72
73 %  my @custom_priorities = ();
74 %  if ( $conf->config('ticket_system-custom_priority_field')
75 %       && @{[ $conf->config('ticket_system-custom_priority_field-values') ]} ) {
76 %    @custom_priorities =
77 %      $conf->config('ticket_system-custom_priority_field-values');
78 %  }
79
80   <BR><BR><% $pager.include('/elements/table-grid.html') %>
81       <TR>
82         <TH CLASS="grid" BGCOLOR="#cccccc"><% mt('#') |h %></TH>
83         <TH CLASS="grid" BGCOLOR="#cccccc"><% mt('Status') |h %></TH>
84         <TH CLASS="grid" BGCOLOR="#cccccc"><% mt('Name') |h %></TH>
85         <TH CLASS="grid" BGCOLOR="#cccccc"><% mt('Company') |h %></TH>
86
87 %foreach my $addl_header ( @addl_headers ) {
88     <TH CLASS="grid" BGCOLOR="#cccccc"><% $addl_header %></TH>
89 %}
90
91         <TH CLASS="grid" BGCOLOR="#cccccc"><% mt('Packages') |h %></TH>
92         <TH CLASS="grid" BGCOLOR="#cccccc" COLSPAN="2"><% mt('Services') |h %></TH>
93      </TR>
94
95 %  my $bgcolor1 = '#eeeeee';
96 %  my $bgcolor2 = '#ffffff';
97 %  my $bgcolor;
98 %
99 %  my(%saw,$cust_main);
100 %  foreach $cust_main (
101 %    sort $sortby grep(!$saw{$_->custnum}++, @cust_main)
102 %  ) {
103 %
104 %    if ( $bgcolor eq $bgcolor1 ) {
105 %      $bgcolor = $bgcolor2;
106 %    } else {
107 %      $bgcolor = $bgcolor1;
108 %    }
109 %
110 %    my($custnum,$last,$first,$company)=(
111 %      $cust_main->custnum,
112 %      $cust_main->getfield('last'),
113 %      $cust_main->getfield('first'),
114 %      $cust_main->company,
115 %    );
116 %
117 %    my @all_cust_svc;
118 %    my @pkg_rowspans;
119 %    foreach my $cust_pkg ( @{$all_pkgs{$custnum}} ) {
120 %      my %cust_svc_by_svcpart;
121 %      my $rows = 0;
122 %      foreach my $part_svc (
123 %        $cust_pkg->part_svc( summarize_size=>$large_pkg_size )
124 %      ) {
125 %        my $svcpart = $part_svc->svcpart;
126 %        my $num_cust_svc = $part_svc->num_cust_svc;
127 %        if ( $large_pkg_size > 0 and $num_cust_svc >= $large_pkg_size ) {
128 %          # don't retrieve the cust_svc records, just stash the 
129 %          # part_svc and num_cust_svc for later
130 %          $cust_svc_by_svcpart{$svcpart} = 
131 %            [ 'summarize', $part_svc, $num_cust_svc ];
132 %          $rows += 2;
133 %        }
134 %        elsif ( $num_cust_svc ) {
135 %          $cust_svc_by_svcpart{$svcpart} = $part_svc->cust_pkg_svc;
136 %          $rows += $num_cust_svc;
137 %        } #if summarize
138 %      } #foreach $part_svc
139 %      $rows ||= 1; # in case the package has no services
140 %      push @all_cust_svc, \%cust_svc_by_svcpart;
141 %      push @pkg_rowspans, $rows;
142 %    } #foreach $cust_pkg
143 %    my $rowspan = List::Util::sum(@pkg_rowspans) || 1;
144 %
145 %    my $view;
146 %    if ( defined $cgi->param('quickpay') && $cgi->param('quickpay') eq 'yes' ) {
147 %      $view = $p. 'edit/cust_pay.cgi?quickpay=yes;custnum='. $custnum;
148 %    } else {
149 %      $view = $p. 'view/cust_main.cgi?'. $custnum;
150 %    }
151 %    my $pcompany = $company
152 %      ? qq!<A HREF="$view"><FONT SIZE=-1>!. encode_entities($company). '</FONT></A>'
153 %      : '<FONT SIZE=-1>&nbsp;</FONT>';
154 %    
155 %    my $status_label = $cust_main->status_label;
156 %    my $statuscolor = $cust_main->statuscolor;
157
158     <TR>
159       <TD CLASS="grid" ALIGN="right" BGCOLOR="<% $bgcolor %>" ROWSPAN=<% $rowspan %>>
160         <A HREF="<% $view %>"><FONT SIZE=-1><% $cust_main->display_custnum %></FONT></A>
161       </TD>
162       <TD CLASS="grid" ALIGN="center" BGCOLOR="<% $bgcolor %>" ROWSPAN=<% $rowspan %>>
163         <FONT SIZE="-1" COLOR="#<% $statuscolor %>"><B><% $status_label %></B></FONT>
164       </TD>
165       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ROWSPAN=<% $rowspan %>>
166         <A HREF="<% $view %>"><FONT SIZE=-1><% "$last, $first" |h %></FONT></A>
167       </TD>
168       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ROWSPAN=<% $rowspan %>>
169         <% $pcompany %>
170       </TD>
171
172 %    foreach my $addl_col ( @addl_cols ) { 
173 % if ( $addl_col eq 'tickets' ) { 
174 % if ( @custom_priorities ) { 
175
176         <TD CLASS="inv" BGCOLOR="<% $bgcolor %>" ROWSPAN=<% $rowspan %> ALIGN=right>
177             <FONT SIZE=-1>
178                <TABLE CLASS="inv" CELLSPACING=0 CELLPADDING=0>
179 % foreach my $priority ( @custom_priorities, '' ) { 
180 %                    my $num =
181 %                      FS::TicketSystem->num_customer_tickets($custnum,$priority);
182 %                    my $ahref = '';
183 %                    $ahref= '<A HREF="'.
184 %                            FS::TicketSystem->href_customer_tickets($custnum,$priority).
185 %                            '">'
186 %                      if $num;
187         
188                  <TR>
189                    <TD ALIGN=right>
190                      <FONT SIZE=-1><% $ahref.$num %></A></FONT>
191                    </TD>
192                    <TD ALIGN=left>
193                      <FONT SIZE=-1><% $ahref %><% $priority || '<i>('.emt('none').')</i>' %></A></FONT>
194                    </TD>
195                  </TR>
196 % } 
197
198              <TR>
199                <TH ALIGN=right STYLE="border-top: dashed 1px black">
200                <FONT SIZE=-1>
201 % } else { 
202           <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ROWSPAN=<% $rowspan %> ALIGN=right>
203             <FONT SIZE=-1>
204 % } 
205 %           my $ahref = '';
206 %           $ahref = '<A HREF="'.
207 %                       FS::TicketSystem->href_customer_tickets($custnum).
208 %                       '">'
209 %             if $cust_main->get($addl_col);
210 %        
211
212         <% $ahref %><% $cust_main->get($addl_col) %></A>
213 % if ( @custom_priorities ) { 
214
215           </FONT></TH>
216             <TH ALIGN=left STYLE="border-top: dashed 1px black">
217               <FONT SIZE=-1><% ${ahref} %>Total</A><FONT>
218             </TH>
219           </TR>
220           </TABLE>
221 % } 
222
223         </FONT></TD>
224 % } else { 
225
226         <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ROWSPAN=<% $rowspan %> ALIGN=right><FONT SIZE=-1>
227           <% $cust_main->get($addl_col) %>
228         </FONT></TD>
229
230 %      }
231 %    }
232
233 %    my $n1 = '';
234 %    foreach ( @{$all_pkgs{$custnum}} ) {
235 %      my $pkgnum = $_->pkgnum;
236 %      my $part_pkg = $_->part_pkg;
237 %
238 %      my $pkg_comment = $part_pkg->pkg_comment( cust_pkg=>$_, nopkgpart=>1 );
239 %      my $show = $curuser->default_customer_view =~ /^(jumbo|packages)$/
240 %                   ? ''
241 %                   : ';show=packages';
242 %      my $frag = "cust_pkg$pkgnum"; #hack for IE ignoring real #fragment
243 %      my $pkgview = "${p}view/cust_main.cgi?custnum=$custnum$show;fragment=$frag#$frag";
244 %      # cust_svc stuff, built earlier
245 %      my %cust_svc_by_svcpart = %{ shift @all_cust_svc };
246 %      my $pkg_rowspan = shift @pkg_rowspans;
247
248         <% $n1 %><TD CLASS="grid" BGCOLOR="<% $bgcolor %>"  ROWSPAN="<% $pkg_rowspan%>">
249             <A HREF="<% $pkgview %>"><FONT SIZE=-1><% $pkg_comment |h %></FONT></A>
250         </TD>
251
252 %       my $n2 = '';
253 %       my $td = '<TD CLASS="grid" BGCOLOR="'.$bgcolor.'">';
254 %
255 %       foreach my $svcpart ( sort keys %cust_svc_by_svcpart ) { #sort order?
256 %         my $these = $cust_svc_by_svcpart{$svcpart};
257 %         if ( $these->[0] eq 'summarize' ) {
258 %           my $part_svc = $these->[1];
259 %           my $num_cust_svc = $these->[2];
260         <% $n2 %>
261 %           # summarize
262 %           # link opens a new search for this pkgnum/svcpart combo
263 %           my $href = $p.'search/cust_pkg_svc.html?svcpart='.$svcpart.
264 %                     ';pkgnum='.$pkgnum;
265           <% $td %>
266             <A HREF="<% $href %>"><% $part_svc->svc %></A>
267           </TD>
268           <% $td %>
269             <A HREF="<% $href %>"><B>(<% mt("view all [_1]", $num_cust_svc) |h %>)</B></A>
270           </TD>
271         </TR><TR>
272           <% $td %></TD>
273           <% $td %><& /elements/search-cust_svc.html, 
274                     'svcpart' => $svcpart,
275                     'pkgnum'  => $pkgnum,
276                     'svcdb'   => $part_svc->svcdb,
277                     &></TD>
278 %           $n2="</TR><TR>";
279 %         }
280 %         elsif ( scalar @$these ) { # do not summarize
281 %           foreach my $cust_svc ( @$these ) {
282           <% $n2 %>
283             <% $td %>
284                 <% FS::UI::Web::svc_link($m, $cust_svc->part_svc, $cust_svc) %>
285             </TD> 
286             <% $td %>
287                 <% FS::UI::Web::svc_label_link($m, $cust_svc->part_svc, $cust_svc) %>
288             </TD>
289 %             $n2="</TR><TR>";
290 %           } #foreach $cust_svc
291 %         }
292 %       } # foreach $svcpart
293 %
294 %      unless ( %cust_svc_by_svcpart ) {
295             <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" COLSPAN=2>&nbsp;</TD>
296 %      }
297 %
298 %      $n1="</TR><TR>";
299 %    }
300 %
301 %    unless ( @{$all_pkgs{$custnum}} ) {
302         <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" COLSPAN=3>&nbsp;</TD>
303 %    }
304 %    
305     </TR>
306 %  }
307  
308   </TABLE><% $pager %>
309
310   <& /elements/footer.html &>
311 <%init>
312 my $curuser = $FS::CurrentUser::CurrentUser;
313
314 die "access denied"
315   unless $curuser->access_right('List all customers');
316
317 my $conf = new FS::Conf;
318 my $maxrecords = $conf->config('maxsearchrecordsperpage');
319 # summarize more than this many services of the same svcpart
320 my $large_pkg_size = $conf->config('cust_pkg-large_pkg_size') || 0;
321
322 my $limit = '';
323 $limit .= "LIMIT $maxrecords" if $maxrecords;
324
325 my $offset = $cgi->param('offset') || 0;
326 $limit .= " OFFSET $offset" if $offset;
327
328 my $total = 0;
329
330 my(@cust_main, $sortby, $orderby);
331 my @select = ();
332 my @addl_headers = ();
333 my @addl_cols = ();
334 if ( $cgi->param('browse')
335      || $cgi->param('otaker_on')
336      || $cgi->param('agentnum_on')
337 ) {
338
339   my %search = ();
340
341   if ( $cgi->param('browse') ) {
342     my $query = $cgi->param('browse');
343     if ( $query eq 'custnum' ) {
344       if ( $conf->exists('cust_main-default_agent_custid') ) {
345         $sortby=\*display_custnum_sort;
346         $orderby = "ORDER BY CASE WHEN agent_custid IS NOT NULL
347                                    AND agent_custid != ''
348                                    AND agent_custid ". regexp_sql. " '^[0-9]+\$'
349                              THEN CAST(agent_custid AS BIGINT)
350                              ELSE custnum
351                              END";
352       } else {
353         $sortby=\*custnum_sort;
354         $orderby = "ORDER BY custnum";
355       }
356     } elsif ( $query eq 'last' ) {
357       $sortby=\*last_sort;
358       $orderby = "ORDER BY LOWER(last || ' ' || first)";
359     } elsif ( $query eq 'company' ) {
360       $sortby=\*company_sort;
361       $orderby = "ORDER BY LOWER(company || ' ' || last || ' ' || first )";
362     } elsif ( $query eq 'tickets' ) {
363       $sortby = \*tickets_sort;
364       $orderby = "ORDER BY tickets DESC";
365       push @select, FS::TicketSystem->sql_num_customer_tickets. " as tickets";
366       push @addl_headers, 'Tickets';
367       push @addl_cols, 'tickets';
368     } elsif ( $query eq 'uspsunvalid' ) {
369        $search{'country'} = 'US';
370        $sortby=\*custnum_sort;
371        $orderby = "ORDER BY custnum";
372     } else {
373       die "unknown browse field $query";
374     }
375   } else {
376     $sortby = \*last_sort; #??
377     $orderby = "ORDER BY LOWER(last || ' ' || first)"; #??
378   }
379
380   if ( $cgi->param('otaker_on') ) {
381     die "access denied"
382       unless $FS::CurrentUser::CurrentUser->access_right('Configuration');
383     $cgi->param('otaker') =~ /^(\w{1,32})$/ or errorpage("Illegal otaker");
384     $search{otaker} = $1;
385   } elsif ( $cgi->param('agentnum_on') ) {
386     $cgi->param('agentnum') =~ /^(\d+)$/ or errorpage("Illegal agentnum");
387     $search{agentnum} = $1;
388   }
389
390   my @qual = ();
391
392   my $ncancelled = '';
393
394   if (  $cgi->param('showcancelledcustomers') eq '0' #see if it was set by me
395        || ( $conf->exists('hidecancelledcustomers')
396              && ! $cgi->param('showcancelledcustomers') )
397      ) {
398     push @qual, FS::cust_main->uncancel_sql;
399    }
400
401   push @qual, FS::cust_main->cancel_sql   if $cgi->param('cancelled');
402   push @qual, FS::cust_main->prospect_sql if $cgi->param('prospect');
403   push @qual, FS::cust_main->ordered_sql  if $cgi->param('ordered');
404   push @qual, FS::cust_main->active_sql   if $cgi->param('active');
405   push @qual, FS::cust_main->inactive_sql if $cgi->param('inactive');
406   push @qual, FS::cust_main->susp_sql     if $cgi->param('suspended');
407
408   #EWWWWWW
409   my $qual = join(' AND ',
410             map { "$_ = ". dbh->quote($search{$_}) } keys %search );
411
412   my $addl_qual = join(' AND ', @qual);
413
414   #here is the agent virtualization
415   $addl_qual .= ( $addl_qual ? ' AND ' : '' ).
416                 $FS::CurrentUser::CurrentUser->agentnums_sql;
417
418   if ( $cgi->param('browse') && $cgi->param('browse') eq 'uspsunvalid' ) {
419        $addl_qual .= ' AND ( length(zip) < 9 OR upper(address1) != address1 OR upper(city) != city ) ';
420   }
421
422   if ( $addl_qual ) {
423     $qual .= ' AND ' if $qual;
424     $qual .= $addl_qual;
425   }
426     
427   $qual = " WHERE $qual" if $qual;
428   my $statement = "SELECT COUNT(*) FROM cust_main $qual";
429   my $sth = dbh->prepare($statement) or die dbh->errstr." preparing $statement";
430   $sth->execute or die "Error executing \"$statement\": ". $sth->errstr;
431
432   $total = $sth->fetchrow_arrayref->[0];
433
434   if ( $addl_qual ) {
435     if ( %search ) {
436       $addl_qual = " AND $addl_qual";
437     } else {
438       $addl_qual = " WHERE $addl_qual";
439     }
440   }
441
442   my $select;
443   if ( @select ) {
444     $select = 'cust_main.*, '. join (', ', @select);
445   } else {
446     $select = '*';
447   }
448
449   @cust_main = qsearch('cust_main', \%search, $select,   
450                          "$addl_qual $orderby $limit" );
451
452 } else {
453   @cust_main=();
454   $sortby = \*last_sort;
455
456   push @cust_main, @{&custnumsearch}
457     if $cgi->param('custnum_on') && $cgi->param('custnum_text');
458   push @cust_main, @{&cardsearch}
459     if $cgi->param('card_on') && $cgi->param('card');
460   push @cust_main, @{&lastsearch}
461     if $cgi->param('last_on') && $cgi->param('last_text');
462   push @cust_main, @{&companysearch}
463     if $cgi->param('company_on') && $cgi->param('company_text');
464   push @cust_main, @{&address2search}
465     if $cgi->param('address2_on') && $cgi->param('address2_text');
466   push @cust_main, @{&phonesearch}
467     if $cgi->param('phone_on') && $cgi->param('phone_text');
468   push @cust_main, @{&referralsearch}
469     if $cgi->param('referral_custnum');
470
471   if ( $cgi->param('company_on') && $cgi->param('company_text') ) {
472     $sortby = \*company_sort;
473     push @cust_main, @{&companysearch};
474   }
475
476   if ( $cgi->param('search_cust') ) {
477     $sortby = \*company_sort;
478     $orderby = "ORDER BY LOWER(company || ' ' || last || ' ' || first )";
479     push @cust_main, smart_search(
480       'search'            => scalar($cgi->param('search_cust')),
481     );
482   }
483
484   @cust_main = grep { $_->num_ncancelled_pkgs || ! $_->num_pkgs } @cust_main
485     if ! $cgi->param('cancelled')
486        && (
487          $cgi->param('showcancelledcustomers') eq '0' #see if it was set by me
488          || ( $conf->exists('hidecancelledcustomers')
489                && ! $cgi->param('showcancelledcustomers') )
490        );
491
492   my %saw = ();
493   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
494 }
495
496 my $pkgs_method = $conf->exists('hidecancelledpackages')
497                     ? 'ncancelled_pkgs'
498                     : 'all_pkgs';
499
500 #false laziness w/httemplate/view/cust_main/packages.html
501 my $select = join(',',
502                'cust_pkg.*',
503                'part_pkg.*',
504                'setup_option.optionvalue AS _opt_setup_fee',
505                'recur_option.optionvalue AS _opt_recur_fee',
506              );
507
508 my $addl_from = qq{
509     LEFT JOIN part_pkg USING ( pkgpart )
510     LEFT JOIN part_pkg_option AS setup_option
511       ON (     cust_pkg.pkgpart = setup_option.pkgpart
512            AND setup_option.optionname = 'setup_fee' )
513     LEFT JOIN part_pkg_option AS recur_option
514       ON (     cust_pkg.pkgpart = recur_option.pkgpart
515            AND recur_option.optionname = 'recur_fee' )
516 };
517
518 my %all_pkgs = map { $_->custnum =>
519                        [ $_->$pkgs_method({ select    => $select,
520                                             addl_from => $addl_from,
521                                          })
522                        ];
523                    }
524                  @cust_main;
525
526 sub last_sort {
527   lc($a->getfield('last')) cmp lc($b->getfield('last'))
528   || lc($a->first) cmp lc($b->first);
529 }
530
531 sub company_sort {
532   return -1 if $a->company && ! $b->company;
533   return 1 if ! $a->company && $b->company;
534   lc($a->company) cmp lc($b->company)
535   || lc($a->getfield('last')) cmp lc($b->getfield('last'))
536   || lc($a->first) cmp lc($b->first);;
537 }
538
539 sub display_custnum_sort {
540   $a->display_custnum <=> $b->display_custnum;
541 }
542
543 sub custnum_sort {
544   $a->getfield('custnum') <=> $b->getfield('custnum');
545 }
546
547 sub tickets_sort {
548   $b->getfield('tickets') <=> $a->getfield('tickets');
549 }
550
551 sub custnumsearch {
552
553   my $custnum = $cgi->param('custnum_text');
554   $custnum =~ s/\D//g;
555   $custnum =~ /^(\d{1,23})$/ or errorpage(emt("Illegal customer number"));
556   $custnum = $1;
557   
558   [ qsearchs('cust_main', { 'custnum' => $custnum } ) ];
559 }
560
561 sub cardsearch {
562
563   my($card)=$cgi->param('card');
564   $card =~ s/\D//g;
565   $card =~ /^(\d{13,16}|\d{8,9})$/ or errorpage(emt("Illegal card number"));
566   my($payinfo)=$1;
567
568   [ qsearch('cust_main',{'payinfo'=>$payinfo, 'payby'=>'CARD'}),
569     qsearch('cust_main',{'payinfo'=>$payinfo, 'payby'=>'DCRD'})
570   ];
571 }
572
573 sub referralsearch {
574   $cgi->param('referral_custnum') =~ /^(\d+)$/
575     or errorpage("Illegal referral_custnum");
576   my $cust_main = qsearchs('cust_main', { 'custnum' => $1 } )
577     or errorpage(emt("Customer [_1] not found",$1));
578   my $depth;
579   if ( $cgi->param('referral_depth') ) {
580     $cgi->param('referral_depth') =~ /^(\d+)$/
581       or errorpage(emt("Illegal referral_depth"));
582     $depth = $1;
583   } else {
584     $depth = 1;
585   }
586   [ $cust_main->referral_cust_main($depth) ];
587 }
588
589 sub lastsearch {
590   my(%last_type);
591   my @cust_main;
592   foreach ( $cgi->param('last_type') ) {
593     $last_type{$_}++;
594   }
595
596   $cgi->param('last_text') =~ /^([\w \,\.\-\']*)$/
597     or errorpage(emt("Illegal last name"));
598   my($last)=$1;
599
600   if ( $last_type{'Exact'} || $last_type{'Fuzzy'} ) {
601     push @cust_main, qsearch( 'cust_main',
602                               { 'last' => { 'op'    => 'ILIKE',
603                                             'value' => $last    } } );
604
605     push @cust_main, qsearch( 'cust_main',
606                               { 'ship_last' => { 'op'    => 'ILIKE',
607                                                  'value' => $last    } } )
608       if defined dbdef->table('cust_main')->column('ship_last');
609   }
610
611   if ( $last_type{'Substring'} || $last_type{'All'} ) {
612
613     push @cust_main, qsearch( 'cust_main',
614                               { 'last' => { 'op'    => 'ILIKE',
615                                             'value' => "%$last%" } } );
616
617     push @cust_main, qsearch( 'cust_main',
618                               { 'ship_last' => { 'op'    => 'ILIKE',
619                                                  'value' => "%$last%" } } )
620       if defined dbdef->table('cust_main')->column('ship_last');
621
622   }
623
624   if ( $last_type{'Fuzzy'} || $last_type{'All'} ) {
625     push @cust_main, FS::cust_main::Search->fuzzy_search( { 'last' => $last } );
626   }
627
628   \@cust_main;
629 }
630
631 sub companysearch {
632
633   my(%company_type);
634   my @cust_main;
635   foreach ( $cgi->param('company_type') ) {
636     $company_type{$_}++ 
637   };
638
639   $cgi->param('company_text') =~
640     /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
641       or errorpage(emt("Illegal company"));
642   my $company = $1;
643
644   if ( $company_type{'Exact'} || $company_type{'Fuzzy'} ) {
645     push @cust_main, qsearch( 'cust_main',
646                               { 'company' => { 'op'    => 'ILIKE',
647                                                'value' => $company } } );
648
649     push @cust_main, qsearch( 'cust_main',
650                               { 'ship_company' => { 'op'    => 'ILIKE',
651                                                     'value' => $company } } )
652       if defined dbdef->table('cust_main')->column('ship_last');
653   }
654
655   if ( $company_type{'Substring'} || $company_type{'All'} ) {
656
657     push @cust_main, qsearch( 'cust_main',
658                               { 'company' => { 'op'    => 'ILIKE',
659                                                'value' => "%$company%" } } );
660
661     push @cust_main, qsearch( 'cust_main',
662                               { 'ship_company' => { 'op'    => 'ILIKE',
663                                                     'value' => "%$company%" } })
664       if defined dbdef->table('cust_main')->column('ship_last');
665
666   }
667
668   if ( $company_type{'Fuzzy'} || $company_type{'All'} ) {
669     push @cust_main, FS::cust_main::Search->fuzzy_search( { 'company' => $company } );
670   }
671
672   if ($company_type{'Sound-alike'}) {
673   }
674
675   \@cust_main;
676 }
677
678 sub address2search {
679   my @cust_main;
680
681   $cgi->param('address2_text') =~
682     /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
683       or errorpage(emt("Illegal address2"));
684   my $address2 = $1;
685
686   push @cust_main, qsearch( 'cust_main',
687                             { 'address2' => { 'op'    => 'ILIKE',
688                                               'value' => $address2 } } );
689   push @cust_main, qsearch( 'cust_main',
690                             { 'ship_address2' => { 'op'    => 'ILIKE',
691                                                    'value' => $address2 } } );
692
693   \@cust_main;
694 }
695
696 sub phonesearch {
697   my @cust_main;
698
699   my $phone = $cgi->param('phone_text');
700
701   $phone =~ s/\D//g;
702   if ( $phone =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/ ) {
703     $phone = "$1-$2-$3";
704     $phone .= " x$4" if $4;
705   } elsif ( $phone =~ /^(\d{3})(\d{4})$/ ) {
706     $phone = "$1-$2";
707   } elsif ( $phone =~ /^(\d{3,4})$/ ) {
708     $phone = $1;
709   } else {
710     errorpage(gettext('illegal_phone'). ": $phone");
711   }
712
713   my @fields = qw(daytime night fax);
714   push @fields, qw(ship_daytime ship_night ship_fax)
715     if defined dbdef->table('cust_main')->column('ship_last');
716
717   for my $field ( @fields ) {
718     push @cust_main, qsearch ( 'cust_main', 
719                                { $field => { 'op'    => 'LIKE',
720                                              'value' => "%$phone%" } } );
721   }
722
723   \@cust_main;
724 }
725 </%init>