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