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