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