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