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