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