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