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