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