combine ticket notification scrips, #15353
[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 %></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('(bill) name') |h %></TH>
85         <TH CLASS="grid" BGCOLOR="#cccccc"><% mt('company') |h %></TH>
86
87 %if ( defined dbdef->table('cust_main')->column('ship_last') ) {
88       <TH CLASS="grid" BGCOLOR="#cccccc"><% mt('(service) name') |h %></TH>
89       <TH CLASS="grid" BGCOLOR="#cccccc"><% mt('company') |h %></TH>
90 %}
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 %      foreach my $part_svc ( $cust_pkg->part_svc ) {
128 %        my $svcpart = $part_svc->svcpart;
129 %        my $num_cust_svc = $cust_pkg->num_cust_svc($svcpart);
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} = [ $cust_pkg->cust_svc($svcpart) ];
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>$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" %></FONT></A>
170       </TD>
171       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ROWSPAN=<% $rowspan %>>
172         <% $pcompany %>
173       </TD>
174
175 %    if ( defined dbdef->table('cust_main')->column('ship_last') ) {
176 %      my($ship_last,$ship_first,$ship_company)=(
177 %        $cust_main->ship_last || $cust_main->getfield('last'),
178 %        $cust_main->ship_last ? $cust_main->ship_first : $cust_main->first,
179 %        $cust_main->ship_last ? $cust_main->ship_company : $cust_main->company,
180 %      );
181 %      my $pship_company = $ship_company
182 %        ? qq!<A HREF="$view"><FONT SIZE=-1>$ship_company</FONT></A>!
183 %        : '<FONT SIZE=-1>&nbsp;</FONT>';
184 %      
185
186       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ROWSPAN=<% $rowspan %>>
187         <A HREF="<% $view %>"><FONT SIZE=-1><% "$ship_last, $ship_first" %></FONT></A>
188       </TD>
189       <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ROWSPAN=<% $rowspan %>>
190         <% $pship_company %></A>
191       </TD>
192 % }
193 %
194 %    foreach my $addl_col ( @addl_cols ) { 
195 % if ( $addl_col eq 'tickets' ) { 
196 % if ( @custom_priorities ) { 
197
198         <TD CLASS="inv" BGCOLOR="<% $bgcolor %>" ROWSPAN=<% $rowspan %> ALIGN=right>
199             <FONT SIZE=-1>
200                <TABLE CLASS="inv" CELLSPACING=0 CELLPADDING=0>
201 % foreach my $priority ( @custom_priorities, '' ) { 
202 %                    my $num =
203 %                      FS::TicketSystem->num_customer_tickets($custnum,$priority);
204 %                    my $ahref = '';
205 %                    $ahref= '<A HREF="'.
206 %                            FS::TicketSystem->href_customer_tickets($custnum,$priority).
207 %                            '">'
208 %                      if $num;
209         
210                  <TR>
211                    <TD ALIGN=right>
212                      <FONT SIZE=-1><% $ahref.$num %></A></FONT>
213                    </TD>
214                    <TD ALIGN=left>
215                      <FONT SIZE=-1><% $ahref %><% $priority || '<i>('.emt('none').')</i>' %></A></FONT>
216                    </TD>
217                  </TR>
218 % } 
219
220              <TR>
221                <TH ALIGN=right STYLE="border-top: dashed 1px black">
222                <FONT SIZE=-1>
223 % } else { 
224           <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ROWSPAN=<% $rowspan %> ALIGN=right>
225             <FONT SIZE=-1>
226 % } 
227 %           my $ahref = '';
228 %           $ahref = '<A HREF="'.
229 %                       FS::TicketSystem->href_customer_tickets($custnum).
230 %                       '">'
231 %             if $cust_main->get($addl_col);
232 %        
233
234         <% $ahref %><% $cust_main->get($addl_col) %></A>
235 % if ( @custom_priorities ) { 
236
237           </FONT></TH>
238             <TH ALIGN=left STYLE="border-top: dashed 1px black">
239               <FONT SIZE=-1><% ${ahref} %>Total</A><FONT>
240             </TH>
241           </TR>
242           </TABLE>
243 % } 
244
245         </FONT></TD>
246 % } else { 
247
248         <TD CLASS="grid" BGCOLOR="<% $bgcolor %>" ROWSPAN=<% $rowspan %> ALIGN=right><FONT SIZE=-1>
249           <% $cust_main->get($addl_col) %>
250         </FONT></TD>
251
252 %      }
253 %    }
254
255 %    my $n1 = '';
256 %    foreach ( @{$all_pkgs{$custnum}} ) {
257 %      my $pkgnum = $_->pkgnum;
258 %      my $part_pkg = $_->part_pkg;
259 %
260 %      my $pkg_comment = $part_pkg->pkg_comment(nopkgpart => 1);
261 %      my $show = $curuser->default_customer_view =~ /^(jumbo|packages)$/
262 %                   ? ''
263 %                   : ';show=packages';
264 %      my $frag = "cust_pkg$pkgnum"; #hack for IE ignoring real #fragment
265 %      my $pkgview = "${p}view/cust_main.cgi?custnum=$custnum$show;fragment=$frag#$frag";
266 %      # cust_svc stuff, built earlier
267 %      my %cust_svc_by_svcpart = %{ shift @all_cust_svc };
268 %      my $pkg_rowspan = shift @pkg_rowspans;
269
270         <% $n1 %><TD CLASS="grid" BGCOLOR="<% $bgcolor %>"  ROWSPAN="<% $pkg_rowspan%>">
271             <A HREF="<% $pkgview %>"><FONT SIZE=-1><% $pkg_comment %></FONT></A>
272         </TD>
273
274 %       my $n2 = '';
275 %       my $td = '<TD CLASS="grid" BGCOLOR="'.$bgcolor.'">';
276 %
277 %       foreach my $svcpart ( sort keys %cust_svc_by_svcpart ) { #sort order?
278 %         my $these = $cust_svc_by_svcpart{$svcpart};
279 %         if ( $these->[0] eq 'summarize' ) {
280 %           my $part_svc = $these->[1];
281 %           my $num_cust_svc = $these->[2];
282         <% $n2 %>
283 %           # summarize
284 %           # link opens a new search for this pkgnum/svcpart combo
285 %           my $href = $p.'search/cust_pkg_svc.html?svcpart='.$svcpart.
286 %                     ';pkgnum='.$pkgnum;
287           <% $td %>
288             <A HREF="<% $href %>"><% $part_svc->svc %></A>
289           </TD>
290           <% $td %>
291             <A HREF="<% $href %>"><B>(<% mt("view all [_1]", $num_cust_svc) |h %>)</B></A>
292           </TD>
293         </TR><TR>
294           <% $td %></TD>
295           <% $td %><& /elements/search-cust_svc.html, 
296                     'svcpart' => $svcpart,
297                     'pkgnum'  => $pkgnum,
298                     'svcdb'   => $part_svc->svcdb,
299                     &></TD>
300 %           $n2="</TR><TR>";
301 %         }
302 %         elsif ( scalar @$these ) { # do not summarize
303 %           foreach my $cust_svc ( @$these ) {
304           <% $n2 %>
305             <% $td %>
306                 <% FS::UI::Web::svc_link($m, $cust_svc->part_svc, $cust_svc) %>
307             </TD> 
308             <% $td %>
309                 <% FS::UI::Web::svc_label_link($m, $cust_svc->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 customers');
338
339 my $conf = new FS::Conf;
340 my $maxrecords = $conf->config('maxsearchrecordsperpage');
341 # summarize more than this many services of the same svcpart
342 my $large_pkg_size = $conf->config('cust_pkg-large_pkg_size') || 0;
343
344 my $limit = '';
345 $limit .= "LIMIT $maxrecords" if $maxrecords;
346
347 my $offset = $cgi->param('offset') || 0;
348 $limit .= " OFFSET $offset" if $offset;
349
350 my $total = 0;
351
352 my(@cust_main, $sortby, $orderby);
353 my @select = ();
354 my @addl_headers = ();
355 my @addl_cols = ();
356 if ( $cgi->param('browse')
357      || $cgi->param('otaker_on')
358      || $cgi->param('agentnum_on')
359 ) {
360
361   my %search = ();
362
363   if ( $cgi->param('browse') ) {
364     my $query = $cgi->param('browse');
365     if ( $query eq 'custnum' ) {
366       if ( $conf->exists('cust_main-default_agent_custid') ) {
367         $sortby=\*display_custnum_sort;
368         $orderby = "ORDER BY CASE WHEN agent_custid IS NOT NULL AND agent_custid != '' THEN CAST(agent_custid AS BIGINT) ELSE custnum END";
369       } else {
370         $sortby=\*custnum_sort;
371         $orderby = "ORDER BY custnum";
372       }
373     } elsif ( $query eq 'last' ) {
374       $sortby=\*last_sort;
375       $orderby = "ORDER BY LOWER(last || ' ' || first)";
376     } elsif ( $query eq 'company' ) {
377       $sortby=\*company_sort;
378       $orderby = "ORDER BY LOWER(company || ' ' || last || ' ' || first )";
379     } elsif ( $query eq 'tickets' ) {
380       $sortby = \*tickets_sort;
381       $orderby = "ORDER BY tickets DESC";
382       push @select, FS::TicketSystem->sql_num_customer_tickets. " as tickets";
383       push @addl_headers, 'Tickets';
384       push @addl_cols, 'tickets';
385     } elsif ( $query eq 'uspsunvalid' ) {
386        $search{'country'} = 'US';
387        $sortby=\*custnum_sort;
388        $orderby = "ORDER BY custnum";
389     } else {
390       die "unknown browse field $query";
391     }
392   } else {
393     $sortby = \*last_sort; #??
394     $orderby = "ORDER BY LOWER(last || ' ' || first)"; #??
395   }
396
397   if ( $cgi->param('otaker_on') ) {
398     die "access denied"
399       unless $FS::CurrentUser::CurrentUser->access_right('Configuration');
400     $cgi->param('otaker') =~ /^(\w{1,32})$/ or errorpage("Illegal otaker");
401     $search{otaker} = $1;
402   } elsif ( $cgi->param('agentnum_on') ) {
403     $cgi->param('agentnum') =~ /^(\d+)$/ or errorpage("Illegal agentnum");
404     $search{agentnum} = $1;
405   }
406
407   my @qual = ();
408
409   my $ncancelled = '';
410
411   if (  $cgi->param('showcancelledcustomers') eq '0' #see if it was set by me
412        || ( $conf->exists('hidecancelledcustomers')
413              && ! $cgi->param('showcancelledcustomers') )
414      ) {
415     push @qual, FS::cust_main->uncancel_sql;
416    }
417
418   push @qual, FS::cust_main->cancel_sql   if $cgi->param('cancelled');
419   push @qual, FS::cust_main->prospect_sql if $cgi->param('prospect');
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( 'search' => scalar($cgi->param('search_cust')),
496                                    'no_fuzzy_on_exact' => 1, #pref?
497                                  );
498   }
499
500   @cust_main = grep { $_->ncancelled_pkgs || ! $_->all_pkgs } @cust_main
501     if ! $cgi->param('cancelled')
502        && (
503          $cgi->param('showcancelledcustomers') eq '0' #see if it was set by me
504          || ( $conf->exists('hidecancelledcustomers')
505                && ! $cgi->param('showcancelledcustomers') )
506        );
507
508   my %saw = ();
509   @cust_main = grep { !$saw{$_->custnum}++ } @cust_main;
510 }
511
512 my %all_pkgs;
513 if ( $conf->exists('hidecancelledpackages' ) ) {
514   %all_pkgs = map { $_->custnum => [ $_->ncancelled_pkgs ] } @cust_main;
515 } else {
516   %all_pkgs = map { $_->custnum => [ $_->all_pkgs ] } @cust_main;
517 }
518
519 sub last_sort {
520   lc($a->getfield('last')) cmp lc($b->getfield('last'))
521   || lc($a->first) cmp lc($b->first);
522 }
523
524 sub company_sort {
525   return -1 if $a->company && ! $b->company;
526   return 1 if ! $a->company && $b->company;
527   lc($a->company) cmp lc($b->company)
528   || lc($a->getfield('last')) cmp lc($b->getfield('last'))
529   || lc($a->first) cmp lc($b->first);;
530 }
531
532 sub display_custnum_sort {
533   $a->display_custnum <=> $b->display_custnum;
534 }
535
536 sub custnum_sort {
537   $a->getfield('custnum') <=> $b->getfield('custnum');
538 }
539
540 sub tickets_sort {
541   $b->getfield('tickets') <=> $a->getfield('tickets');
542 }
543
544 sub custnumsearch {
545
546   my $custnum = $cgi->param('custnum_text');
547   $custnum =~ s/\D//g;
548   $custnum =~ /^(\d{1,23})$/ or errorpage(emt("Illegal customer number"));
549   $custnum = $1;
550   
551   [ qsearchs('cust_main', { 'custnum' => $custnum } ) ];
552 }
553
554 sub cardsearch {
555
556   my($card)=$cgi->param('card');
557   $card =~ s/\D//g;
558   $card =~ /^(\d{13,16}|\d{8,9})$/ or errorpage(emt("Illegal card number"));
559   my($payinfo)=$1;
560
561   [ qsearch('cust_main',{'payinfo'=>$payinfo, 'payby'=>'CARD'}),
562     qsearch('cust_main',{'payinfo'=>$payinfo, 'payby'=>'DCRD'})
563   ];
564 }
565
566 sub referralsearch {
567   $cgi->param('referral_custnum') =~ /^(\d+)$/
568     or errorpage("Illegal referral_custnum");
569   my $cust_main = qsearchs('cust_main', { 'custnum' => $1 } )
570     or errorpage(emt("Customer [_1] not found",$1));
571   my $depth;
572   if ( $cgi->param('referral_depth') ) {
573     $cgi->param('referral_depth') =~ /^(\d+)$/
574       or errorpage(emt("Illegal referral_depth"));
575     $depth = $1;
576   } else {
577     $depth = 1;
578   }
579   [ $cust_main->referral_cust_main($depth) ];
580 }
581
582 sub lastsearch {
583   my(%last_type);
584   my @cust_main;
585   foreach ( $cgi->param('last_type') ) {
586     $last_type{$_}++;
587   }
588
589   $cgi->param('last_text') =~ /^([\w \,\.\-\']*)$/
590     or errorpage(emt("Illegal last name"));
591   my($last)=$1;
592
593   if ( $last_type{'Exact'} || $last_type{'Fuzzy'} ) {
594     push @cust_main, qsearch( 'cust_main',
595                               { 'last' => { 'op'    => 'ILIKE',
596                                             'value' => $last    } } );
597
598     push @cust_main, qsearch( 'cust_main',
599                               { 'ship_last' => { 'op'    => 'ILIKE',
600                                                  'value' => $last    } } )
601       if defined dbdef->table('cust_main')->column('ship_last');
602   }
603
604   if ( $last_type{'Substring'} || $last_type{'All'} ) {
605
606     push @cust_main, qsearch( 'cust_main',
607                               { 'last' => { 'op'    => 'ILIKE',
608                                             'value' => "%$last%" } } );
609
610     push @cust_main, qsearch( 'cust_main',
611                               { 'ship_last' => { 'op'    => 'ILIKE',
612                                                  'value' => "%$last%" } } )
613       if defined dbdef->table('cust_main')->column('ship_last');
614
615   }
616
617   if ( $last_type{'Fuzzy'} || $last_type{'All'} ) {
618     push @cust_main, FS::cust_main::Search->fuzzy_search( { 'last' => $last } );
619   }
620
621   \@cust_main;
622 }
623
624 sub companysearch {
625
626   my(%company_type);
627   my @cust_main;
628   foreach ( $cgi->param('company_type') ) {
629     $company_type{$_}++ 
630   };
631
632   $cgi->param('company_text') =~
633     /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
634       or errorpage(emt("Illegal company"));
635   my $company = $1;
636
637   if ( $company_type{'Exact'} || $company_type{'Fuzzy'} ) {
638     push @cust_main, qsearch( 'cust_main',
639                               { 'company' => { 'op'    => 'ILIKE',
640                                                'value' => $company } } );
641
642     push @cust_main, qsearch( 'cust_main',
643                               { 'ship_company' => { 'op'    => 'ILIKE',
644                                                     'value' => $company } } )
645       if defined dbdef->table('cust_main')->column('ship_last');
646   }
647
648   if ( $company_type{'Substring'} || $company_type{'All'} ) {
649
650     push @cust_main, qsearch( 'cust_main',
651                               { 'company' => { 'op'    => 'ILIKE',
652                                                'value' => "%$company%" } } );
653
654     push @cust_main, qsearch( 'cust_main',
655                               { 'ship_company' => { 'op'    => 'ILIKE',
656                                                     'value' => "%$company%" } })
657       if defined dbdef->table('cust_main')->column('ship_last');
658
659   }
660
661   if ( $company_type{'Fuzzy'} || $company_type{'All'} ) {
662     push @cust_main, FS::cust_main::Search->fuzzy_search( { 'company' => $company } );
663   }
664
665   if ($company_type{'Sound-alike'}) {
666   }
667
668   \@cust_main;
669 }
670
671 sub address2search {
672   my @cust_main;
673
674   $cgi->param('address2_text') =~
675     /^([\w \!\@\#\$\%\&\(\)\-\+\;\:\'\"\,\.\?\/\=]*)$/
676       or errorpage(emt("Illegal address2"));
677   my $address2 = $1;
678
679   push @cust_main, qsearch( 'cust_main',
680                             { 'address2' => { 'op'    => 'ILIKE',
681                                               'value' => $address2 } } );
682   push @cust_main, qsearch( 'cust_main',
683                             { 'ship_address2' => { 'op'    => 'ILIKE',
684                                                    'value' => $address2 } } );
685
686   \@cust_main;
687 }
688
689 sub phonesearch {
690   my @cust_main;
691
692   my $phone = $cgi->param('phone_text');
693
694   $phone =~ s/\D//g;
695   if ( $phone =~ /^(\d{3})(\d{3})(\d{4})(\d*)$/ ) {
696     $phone = "$1-$2-$3";
697     $phone .= " x$4" if $4;
698   } elsif ( $phone =~ /^(\d{3})(\d{4})$/ ) {
699     $phone = "$1-$2";
700   } elsif ( $phone =~ /^(\d{3,4})$/ ) {
701     $phone = $1;
702   } else {
703     errorpage(gettext('illegal_phone'). ": $phone");
704   }
705
706   my @fields = qw(daytime night fax);
707   push @fields, qw(ship_daytime ship_night ship_fax)
708     if defined dbdef->table('cust_main')->column('ship_last');
709
710   for my $field ( @fields ) {
711     push @cust_main, qsearch ( 'cust_main', 
712                                { $field => { 'op'    => 'LIKE',
713                                              'value' => "%$phone%" } } );
714   }
715
716   \@cust_main;
717 }
718 </%init>