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