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