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