doc
[freeside.git] / httemplate / search / elements / search.html
1 <%doc>
2
3 Example:
4
5   include( 'elements/search.html',
6
7     ###
8     # required
9     ###
10
11     'title'         => 'Page title',
12     
13     'name_singular' => 'item',  #singular name for the records returned
14        #OR#                     # (preferred, will be pluralized automatically)
15     'name'          => 'items', #plural name for the records returned
16                                 # (deprecated, will be singularlized
17                                 #  simplisticly)
18
19     #literal SQL query string (deprecated?) or qsearch hashref
20     'query'       => {
21                        'table'     => 'tablename',
22                        #everything else is optional...
23                        'hashref'   => { 'field' => 'value',
24                                         'field' => { 'op'    => '<',
25                                                      'value' => '54',
26                                                    },
27                                       },
28                        'select'    => '*',
29                        'addl_from' => '', #'LEFT JOIN othertable USING ( key )',
30                        'extra_sql' => '', #'AND otherstuff', #'WHERE onlystuff',
31                        'order_by'  => 'ORDER BY something',
32    
33                      },
34                      # "select * from tablename";
35    
36     #required unless 'query' is an SQL query string (shouldn't be...)
37     'count_query' => 'SELECT COUNT(*) FROM tablename',
38
39     ###
40     # recommended / common
41     ###
42
43     #listref of column labels, <TH>
44     #recommended unless 'query' is an SQL query string
45     # (if not specified the database column names will be used)
46     'header'      => [ '#',
47                        'Item',
48                        { 'label' => 'Another Item',
49                          
50                        },
51                      ],
52
53     #listref - each item is a literal column name (or method) or coderef
54     #if not specified all columns will be shown
55     'fields'      => [
56                        'column',
57                        sub { my $row = shift; $row->column; },
58                      ],
59
60     #redirect if there's only one item...
61     # listref of URL base and column name (or method)
62     # or a coderef that returns the same
63     'redirect' =>
64    
65     ###
66     # optional
67     ###
68    
69     # some HTML callbacks...
70     'menubar'          => '', #menubar arrayref
71     'html_init'        => '', #after the header/menubar and before the pager
72     'html_form'        => '', #after the pager, right before the results
73                               # (only shown if there are results)
74                               # (use this for any form-opening tag rather than
75                               #  html_init, to avoid a nested form)
76     'html_foot'        => '', #at the bottom
77     'html_posttotal'   => '', #at the bottom
78                               # (these three can be strings or coderefs)
79     
80     'count_addl' => [], #additional count fields listref of sprintf strings or coderefs
81                         # [ $money_char.'%.2f total paid', ],
82    
83     #second (smaller) header line, currently only for HTML
84     'header2      => [ '#',
85                        'Item',
86                        { 'label' => 'Another Item',
87                          
88                        },
89                      ],
90
91     #listref of column footers
92     'footer'      => [],
93     
94     #disabling things
95     'disable_download' => '', # set true to hide the CSV/Excel download links
96     'disable_nonefound' => '', # set true to disable the "No matching Xs found"
97                                # message
98    
99     #handling "disabled" fields in the records
100     'disableable' => 1,  # set set to 1 (or column position for "disabled"
101                          # status col) to enable if this table has a "disabled"
102                          # field, to hide disabled records & have
103                          # "show disabled/hide disabled" links
104                          #(can't be used with a literal query)
105     'disabled_statuspos' => 3, #optional position (starting from 0) to insert
106                                #a Status column when showing disabled records
107                                #(query needs to be a qsearch hashref and
108                                # header & fields need to be defined)
109
110     #handling agent virtualization
111     'agent_virt' => 1, # set true if this search should be agent-virtualized
112     'agent_null_right' => 'Access Right', #opt. right to view global records
113     'agent_pos' => 3, #optional position (starting from 0) to insert
114                       #an Agent column 
115                       #(query needs to be a qsearch hashref and
116                       # header & fields need to be defined)
117
118     # link & display properties for fields
119    
120     #listref - each item is the empty string,
121     #          or a listref of link and method name to append,
122     #          or a listref of link and coderef to run and append
123     #          or a coderef that returns such a listref
124     'links'       => [],`
125
126     #listref - each item is the empty string,
127     #          or a string onClick handler for the corresponding link
128     #          or a coderef that returns string onClick handler
129     'link_onclicks' => [],
130
131     #one letter for each column, left/right/center/none
132     # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
133     'align'       => 'lrc.',
134    
135     #listrefs of ( scalars or coderefs )
136     #currently only HTML, maybe eventually Excel too
137     'color'       => [],
138     'size'        => [],
139     'style'       => [], #<B> or <I>, etc.
140     'cell_style'  => [], #STYLE= attribute of TR, very HTML-specific...
141     
142   );
143
144 </%doc>
145 % if ( $type eq 'csv' ) {
146 %
147 %   #http_header('Content-Type' => 'text/comma-separated-values' ); #IE chokes
148 %   http_header('Content-Type' => 'text/plain' );
149 %
150 %   my $csv = new Text::CSV_XS { 'always_quote' => 1,
151 %                                'eol'          => "\n", #"\015\012", #"\012"
152 %                              };
153 %
154 %   $csv->combine(@$header); #or die $csv->status;
155 %    
156 <% $csv->string %>
157 %
158 %
159 %   foreach my $row ( @$rows ) {
160 %
161 %     if ( $opt{'fields'} ) {
162 %
163 %       my @line = ();
164 %
165 %       foreach my $field ( @{$opt{'fields'}} ) {
166 %         if ( ref($field) eq 'CODE' ) {
167 %           push @line, map {
168 %                             ref($_) eq 'ARRAY'
169 %                               ? '(N/A)' #unimplemented
170 %                               : $_;
171 %                           }
172 %                           &{$field}($row);
173 %         } else {
174 %           push @line, $row->$field();
175 %         }
176 %       }
177 %
178 %       $csv->combine(@line); #or die $csv->status;
179 %
180 %     } else {
181 %       $csv->combine(@$row); #or die $csv->status;
182 %     }
183 %
184 %      
185 <% $csv->string %>
186 %
187 %
188 %   }
189 %
190 % #} elsif ( $type eq 'excel' ) {
191 % } elsif ( $type =~ /\.xls$/ ) {
192 %
193 %   #http_header('Content-Type' => 'application/excel' ); #eww
194 %   #http_header('Content-Type' => 'application/msexcel' ); #alas
195 %   #http_header('Content-Type' => 'application/x-msexcel' ); #?
196 %
197 %   #http://support.microsoft.com/kb/199841
198 %   http_header('Content-Type' => 'application/vnd.ms-excel' );
199 %
200 %   #http://support.microsoft.com/kb/812935
201 %   #http://support.microsoft.com/kb/323308
202 %   $HTML::Mason::Commands::r->headers_out->{'Cache-control'} = 'max-age=0';
203 %
204 %   my $data = '';
205 %   my $XLS = new IO::Scalar \$data;
206 %   my $workbook = Spreadsheet::WriteExcel->new($XLS)
207 %     or die "Error opening .xls file: $!";
208 %
209 %   my $worksheet = $workbook->add_worksheet(substr($opt{'title'},0,31));
210 %
211 %   my($r,$c) = (0,0);
212 %
213 %   $worksheet->write($r, $c++, $_) foreach @$header;
214 %
215 %   foreach my $row ( @$rows ) {
216 %     $r++;
217 %     $c = 0;
218 %
219 %     if ( $opt{'fields'} ) {
220 %
221 %       #my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
222 %       #my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
223 %
224 %       foreach my $field ( @{$opt{'fields'}} ) {
225 %         #my $align = $aligns ? shift @$aligns : '';
226 %         #$align = " ALIGN=$align" if $align;
227 %         #my $a = '';
228 %         #if ( $links ) {
229 %         #  my $link = shift @$links;
230 %         #  $link = &{$link}($row) if ref($link) eq 'CODE';
231 %         #  if ( $link ) {
232 %         #    my( $url, $method ) = @{$link};
233 %         #    if ( ref($method) eq 'CODE' ) {
234 %         #      $a = $url. &{$method}($row);
235 %         #    } else {
236 %         #      $a = $url. $row->$method();
237 %         #    }
238 %         #    $a = qq(<A HREF="$a">);
239 %         #  }
240 %         #}
241 %         if ( ref($field) eq 'CODE' ) {
242 %           foreach my $value ( &{$field}($row) ) {
243 %             if ( ref($value) eq 'ARRAY' ) { 
244 %               $worksheet->write($r, $c++, '(N/A)' ); #unimplemented
245 %             } else {
246 %               $worksheet->write($r, $c++, $value );
247 %             }
248 %           }
249 %         } else {
250 %           $worksheet->write($r, $c++, $row->$field() );
251 %         }
252 %       }
253 %
254 %     } else {
255 %       $worksheet->write($r, $c++, $_) foreach @$row;
256 %     }
257 %
258 %   }
259 %
260 %   $workbook->close();# or die "Error creating .xls file: $!";
261 %
262 %   http_header('Content-Length' => length($data) );
263 %    
264 <% $data %>
265 %
266 %
267 % } else { # regular HTML
268 %
269 %   if ( exists($opt{'redirect'}) && scalar(@$rows) == 1 && $total == 1
270 %        && $type ne 'html-print'
271 %      ) {
272 %     my $redirect = $opt{'redirect'};
273 %     $redirect = &{$redirect}($rows->[0]) if ref($redirect) eq 'CODE';
274 %     my( $url, $method ) = @$redirect;
275 %     redirect( $url. $rows->[0]->$method() );
276 %   } else {
277 %     if ( $opt{'name_singular'} ) {
278 %       $opt{'name'} = PL($opt{'name_singular'});
279 %     }
280 %     ( my $xlsname = $opt{'name'} ) =~ s/\W//g;
281 %     if ( $total == 1 ) {
282 %       if ( $opt{'name_singular'} ) {
283 %         $opt{'name'} = $opt{'name_singular'}
284 %       } else {
285 %         #$opt{'name'} =~ s/s$// if $total == 1;
286 %         $opt{'name'} =~ s/((s)e)?s$/$2/ if $total == 1;
287 %       }
288 %     }
289 %
290 %     if ( $type eq 'html-print' ) {
291
292         <% include( '/elements/header-popup.html', $opt{'title'} ) %>
293
294 %     } else {
295 %
296 %       my @menubar = ();
297 %       if ( $opt{'menubar'} ) {
298 %         @menubar = @{ $opt{'menubar'} };
299 %       #} else {
300 %       #  @menubar = ( 'Main menu' => $p );
301 %       }
302
303         <% include( '/elements/header.html', $opt{'title'},
304                       include( '/elements/menubar.html', @menubar )
305                   )
306         %>
307
308         <% defined($opt{'html_init'}) 
309               ? ( ref($opt{'html_init'})
310                     ? &{$opt{'html_init'}}()
311                     : $opt{'html_init'}
312                 )
313               : ''
314         %>
315
316 %     }
317
318 %     unless ( $total ) { 
319 %       unless ( $opt{'disable_nonefound'} ) { 
320           No matching <% $opt{'name'} %> found.<BR>
321 %       } 
322 %     } else { 
323
324         <TABLE>
325           <TR>
326
327             <TD VALIGN="bottom">
328
329               <FORM>
330
331                 <% $total %> total <% $opt{'name'} %>
332
333 %               if ( $confmax && $total > $confmax && $type ne 'html-print' ) {
334 %                 $cgi->delete('maxrecords');
335 %                 $cgi->param('_dummy', 1);
336
337 %#                 ( show <SELECT NAME="maxrecords" onChange="this.form.submit();">
338                   ( show <SELECT NAME="maxrecords" onChange="window.location = '<% $cgi->self_url %>;maxrecords=' + this.options[this.selectedIndex].value;">
339
340 %                   foreach my $max ( map { $_ * $confmax } qw( 1 5 10 25 ) ) {
341                   <OPTION VALUE="<% $max %>" <% ( $maxrecords == $max ) ? 'SELECTED' : '' %>><% $max %></OPTION>
342 %                   }
343
344                   </SELECT> per page )
345
346 %                 $cgi->param('maxrecords', $maxrecords);
347 %               }
348
349 %               if ( defined($opt{'html_posttotal'}) && $type ne 'html-print' ) {
350                     <% ref($opt{'html_posttotal'})
351                          ? &{$opt{'html_posttotal'}}()
352                          : $opt{'html_posttotal'}
353                     %>
354 %               }
355                 <BR>
356
357 %               if ( $opt{'count_addl'} ) { 
358 %                 my $n=0;
359 %                 foreach my $count ( @{$opt{'count_addl'}} ) { 
360 %                   my $data = $count_arrayref->[++$n];
361 %                   if ( ref($count) ) {
362                       <% &{ $count }( $data ) %>
363 %                   } else {
364                       <% sprintf( $count, $data ) %><BR>
365 %                   }
366 %                 } 
367 %               } 
368               </FORM>
369
370             </TD>
371
372 %           unless ( $opt{'disable_download'} || $type eq 'html-print' ) { 
373
374               <TD ALIGN="right">
375
376                 Download full results<BR>
377
378 %               $cgi->param('_type', "$xlsname.xls" ); 
379                 as <A HREF="<% $cgi->self_url %>">Excel spreadsheet</A><BR>
380
381 %               $cgi->param('_type', 'csv'); 
382                 as <A HREF="<% $cgi->self_url %>">CSV file</A><BR>
383
384 %               $cgi->param('_type', 'html-print'); 
385                 as <A HREF="<% $cgi->self_url %>">printable copy</A>
386
387               </TD>
388 %             $cgi->param('_type', "html" ); 
389 %           } 
390
391           </TR>
392           <TR>
393             <TD COLSPAN=2>
394
395 %             my $pager = '';
396 %             unless ( $type eq 'html_print' ) {
397
398                 <% $pager = include( '/elements/pager.html',
399                                        'offset'     => $offset,
400                                        'num_rows'   => scalar(@$rows),
401                                        'total'      => $total,
402                                        'maxrecords' => $maxrecords,
403                                    )
404                 %>
405
406                 <% defined($opt{'html_form'}) 
407                      ? ( ref($opt{'html_form'})
408                            ? &{$opt{'html_form'}}()
409                            : $opt{'html_form'}
410                        )
411                      : ''
412                 %>
413
414 %             }
415
416               <% include('/elements/table-grid.html') %>
417
418                 <TR>
419 %                 my $h2 = 0;
420 %                 foreach my $header ( @{ $opt{header} } ) { 
421 %                   my $label = ref($header) ? $header->{label} : $header;
422 %                   my $rowspan = 1;
423 %                   my $style = '';
424 %                   if ( $opt{header2} ) {
425 %                     if ( !length($opt{header2}->[$h2]) ) {
426 %                       $rowspan = 2;
427 %                       splice @{ $opt{header2} }, $h2, 1;
428 %                     } else {
429 %                       $h2++;
430 %                       $style = 'STYLE="border-bottom: none"'
431 %                     }
432 %                   }
433                     <TH CLASS   = "grid"
434                         BGCOLOR = "#cccccc"
435                         ROWSPAN = "<% $rowspan %>"
436                         <% $style %>
437
438                     >
439                       <% $label %>
440                     </TH>
441 %                 } 
442                 </TR>
443
444 %               if ( $opt{header2} ) {
445                   <TR>
446 %                   foreach my $header ( @{ $opt{header2} } ) { 
447 %                     my $label = ref($header) ? $header->{label} : $header;
448                       <TH CLASS="grid" BGCOLOR="#cccccc">
449                         <FONT SIZE="-1"><% $label %></FONT>
450                       </TH>
451 %                   } 
452                   </TR>
453 %               }
454
455 %               my $bgcolor1 = '#eeeeee';
456 %               my $bgcolor2 = '#ffffff';
457 %               my $bgcolor;
458 %
459 %               foreach my $row ( @$rows ) {
460 %
461 %                 if ( $bgcolor eq $bgcolor1 ) {
462 %                   $bgcolor = $bgcolor2;
463 %                 } else {
464 %                   $bgcolor = $bgcolor1;
465 %                 }
466
467                   <TR>
468
469 %                   if ( $opt{'fields'} ) {
470 %
471 %                     my $links    = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
472 %                     my $onclicks = $opt{'link_onclicks'} ? [ @{$opt{'link_onclicks'}} ] : [];
473 %                     my $aligns   = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
474 %                     my $colors   = $opt{'color'} ? [ @{$opt{'color'}} ] : [];
475 %                     my $sizes    = $opt{'size'}  ? [ @{$opt{'size'}}  ] : [];
476 %                     my $styles   = $opt{'style'} ? [ @{$opt{'style'}} ] : [];
477 %                     my $cstyles  = $opt{'cell_style'} ? [ @{$opt{'cell_style'}} ] : [];
478 %
479 %                     foreach my $field (
480 %
481 %                       map {
482 %                             if ( ref($_) eq 'ARRAY' ) {
483 %
484 %                               my $tableref = $_;
485 %
486 %                               '<TABLE CLASS="inv" CELLSPACING=0 CELLPADDING=0 WIDTH="100%">'.
487 %
488 %                               join('', map {
489 %
490 %                                 my $rowref = $_;
491 %
492 %                                 '<tr>'.
493 %
494 %                                 join('', map {
495 %
496 %                                   my $e = $_;
497 %
498 %                                   '<TD '.
499 %                                     join(' ', map {
500 %                                       uc($_).'="'. $e->{$_}. '"';
501 %                                     }
502 %                                     grep exists($e->{$_}),
503 %                                          qw( align bgcolor colspan rowspan
504 %                                              style valign width )
505 %                                     ).
506 %                                   '>'.
507 %
508 %                                   ( $e->{'link'}
509 %                                       ? '<A HREF="'. $e->{'link'}. '">'
510 %                                       : ''
511 %                                   ).
512 %                                   ( $e->{'size'}
513 %                                      ? '<FONT SIZE="'.uc($e->{'size'}).'">'
514 %                                      : ''
515 %                                   ).
516 %                                   ( $e->{'data_style'}
517 %                                       ? '<'. uc($e->{'data_style'}). '>'
518 %                                       : ''
519 %                                   ).
520 %                                   $e->{'data'}.
521 %                                   ( $e->{'data_style'}
522 %                                       ? '</'. uc($e->{'data_style'}). '>'
523 %                                       : ''
524 %                                   ).
525 %                                   ( $e->{'size'} ? '</FONT>' : '' ).
526 %                                   ( $e->{'link'} ? '</A>'    : '' ).
527 %                                   '</td>';
528 %
529 %                                 } @$rowref ).
530 %
531 %                                 '</tr>';
532 %                               } @$tableref ).
533 %
534 %                               '</table>';
535 %
536 %                             } else {
537 %                               $_;
538 %                             }
539 %                           }
540 %
541 %                       map {
542 %                             if ( ref($_) eq 'CODE' ) {
543 %                               &{$_}($row);
544 %                             } else {
545 %                               $row->$_();
546 %                             }
547 %                           }
548 %                       @{$opt{'fields'}}
549 %
550 %                     ) {
551 %
552 %                       my $class = ( $field =~ /^<TABLE/i ) ? 'inv' : 'grid';
553 %
554 %                       my $align = $aligns ? shift @$aligns : '';
555 %                       $align = " ALIGN=$align" if $align;
556 %
557 %                       my $a = '';
558 %                       if ( $links ) {
559 %                         my $link = shift @$links;
560 %                         $link = &{$link}($row)
561 %                           if ref($link) eq 'CODE';
562 %
563 %                         my $onclick = shift @$onclicks;
564 %                         $onclick = &{$onclick}($row)
565 %                           if ref($onclick) eq 'CODE';
566 %                         $onclick = qq( onClick="$onclick") if $onclick;
567 %
568 %                         if ( $link ) {
569 %                           my( $url, $method ) = @{$link};
570 %                           if ( ref($method) eq 'CODE' ) {
571 %                             $a = $url. &{$method}($row);
572 %                           } else {
573 %                             $a = $url. $row->$method();
574 %                           }
575 %                           $a = qq(<A HREF="$a"$onclick>);
576 %                         }
577 %                       }
578 %
579 %                       my $font = '';
580 %                       my $color = shift @$colors;
581 %                       $color = &{$color}($row) if ref($color) eq 'CODE';
582 %                       my $size = shift @$sizes;
583 %                       $size = &{$size}($row) if ref($size) eq 'CODE';
584 %                       if ( $color || $size ) {
585 %                         $font = '<FONT '.
586 %                                 ( $color ? "COLOR=#$color "   : '' ).
587 %                                 ( $size  ? qq(SIZE="$size" )  : '' ).
588 %                                 '>';
589 %                       }
590 %
591 %                       my($s, $es) = ( '', '' );
592 %                       my $style = shift @$styles;
593 %                       $style = &{$style}($row) if ref($style) eq 'CODE';
594 %                       if ( $style ) {
595 %                         $s = join( '', map "<$_>", split('', $style) );
596 %                         $es = join( '', map "</$_>", split('', $style) );
597 %                       }
598 %
599 %                       my $cstyle = shift @$cstyles;
600 %                       $cstyle = &{$cstyle}($row) if ref($cstyle) eq 'CODE';
601 %                       $cstyle = qq(STYLE="$cstyle")
602 %                         if $cstyle;
603
604                         <TD CLASS="<% $class %>" BGCOLOR="<% $bgcolor %>" <% $align %> <% $cstyle %>><% $font %><% $a %><% $s %><% $field %><% $es %><% $a ? '</A>' : '' %><% $font ? '</FONT>' : '' %></TD>
605
606 %                     } 
607 %
608 %                   } else { 
609 %
610 %                     foreach ( @$row ) { 
611                         <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $_ %></TD>
612 %                     }
613 %
614 %                   }
615
616                   </TR>
617
618 %               } 
619
620 %               if ( $opt{'footer'} ) { 
621
622                   <TR>
623
624 %                   foreach my $footer ( @{ $opt{'footer'} } ) { 
625                       <TD CLASS="grid" BGCOLOR="#dddddd" STYLE="border-top: dashed 1px black;"><i><% $footer %></i></TD>
626 %                   } 
627
628                   </TR>
629 %               } 
630             
631               </TABLE>
632
633               <% $pager %>
634   
635             </TD>
636           </TR>
637         </TABLE>
638 %     }
639
640 %     if ( $type eq 'html-print' ) {
641
642         </BODY></HTML>
643       
644 %     } else {
645
646         <% defined($opt{'html_foot'}) 
647               ? ( ref($opt{'html_foot'})
648                     ? &{$opt{'html_foot'}}()
649                     : $opt{'html_foot'}
650                 )
651               : ''
652         %>
653
654         <% include( '/elements/footer.html' ) %>
655
656 %     }
657
658 %   } 
659 %
660 % } 
661 <%init>
662
663 my(%opt) = @_;
664 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
665
666 my $curuser = $FS::CurrentUser::CurrentUser;
667
668 my %align = (
669   'l' => 'left',
670   'r' => 'right',
671   'c' => 'center',
672   ' ' => '',
673   '.' => '',
674 );
675 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
676   unless !$opt{align} || ref($opt{align});
677
678 if ( $opt{'agent_virt'} ) {
679
680   my $agentnums_sql = $curuser->agentnums_sql(
681                         'null_right' => $opt{'agent_null_right'}
682                       );
683
684   $opt{'query'}{'extra_sql'} .=
685     ( $opt{'query'}       =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
686     $agentnums_sql;
687   $opt{'count_query'} .=
688     ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
689     $agentnums_sql;
690
691   if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
692        and scalar($curuser->agentnums) > 1           ) {
693     #false laziness w/statuspos above
694     my $pos = $opt{'agent_pos'};
695
696     foreach my $att (qw( align style color size )) {
697       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
698     }
699
700     splice @{ $opt{'header'} }, $pos, 0, 'Agent'; 
701     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
702     splice @{ $opt{'style'}  }, $pos, 0, ''; 
703     splice @{ $opt{'size'}   }, $pos, 0, ''; 
704     splice @{ $opt{'fields'} }, $pos, 0,
705       sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
706     splice @{ $opt{'color'}  }, $pos, 0, '';
707     splice @{ $opt{'links'}  }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
708       if $opt{'links'};
709     splice @{ $opt{'link_onclicks'}  }, $pos, 0, ''
710       if $opt{'link_onclicks'};
711
712   }
713
714 }
715
716 if ( $opt{'disableable'} ) {
717
718   unless ( $cgi->param('showdisabled') ) { #modify searches
719
720     $opt{'query'}{'hashref'}{'disabled'} = '';
721     $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
722
723     $opt{'count_query'} .=
724       ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
725       "( disabled = '' OR disabled IS NULL )";
726
727   } elsif (    $opt{'disabled_statuspos'}
728             || $opt{'disabled_statuspos'} eq '0' ) { #add status column
729
730     my $pos = $opt{'disabled_statuspos'};
731
732     foreach my $att (qw( align style color size )) {
733       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
734     }
735
736     splice @{ $opt{'header'} }, $pos, 0, 'Status'; 
737     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
738     splice @{ $opt{'style'}  }, $pos, 0, 'b'; 
739     splice @{ $opt{'size'}   }, $pos, 0, ''; 
740     splice @{ $opt{'fields'} }, $pos, 0,
741       sub { shift->disabled ? 'DISABLED' : 'Active'; };
742     splice @{ $opt{'color'}  }, $pos, 0,
743       sub { shift->disabled ? 'FF0000'   : '00CC00'; };
744     splice @{ $opt{'links'}  }, $pos, 0, ''
745       if $opt{'links'};
746     splice @{ $opt{'link_onlicks'}  }, $pos, 0, ''
747       if $opt{'link_onlicks'};
748   }
749
750   #add show/hide disabled links
751   my $items = $opt{'name'} || PL($opt{'name_singular'});
752   if ( $cgi->param('showdisabled') ) {
753     $cgi->param('showdisabled', 0);
754     $opt{'html_posttotal'} .=
755       '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!;
756     $cgi->param('showdisabled', 1);
757   } else {
758     $cgi->param('showdisabled', 1);
759     $opt{'html_posttotal'} .=
760       '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!;
761     $cgi->param('showdisabled', 0);
762   }
763
764 }
765
766 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|html(-print)?)$/
767            ? $1 : 'html';
768
769 my $limit = '';
770 my($confmax, $maxrecords, $total, $offset, $count_arrayref);
771
772 unless ( $type =~ /^(csv|\w*\.xls)$/ ) {
773
774   unless (exists($opt{count_query}) && length($opt{count_query})) {
775     ( $opt{count_query} = $opt{query} ) =~
776       s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
777   }
778
779   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
780     $opt{count_query} .=
781       ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
782       "( disabled = '' OR disabled IS NULL )";
783   }
784
785   unless ( $type eq 'html-print' ) {
786
787     #setup some pagination things if we're in html mode
788
789     my $conf = new FS::Conf;
790     $confmax = $conf->config('maxsearchrecordsperpage');
791     if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
792       $maxrecords = $1;
793     } else {
794       $maxrecords ||= $confmax;
795     }
796
797     $limit = $maxrecords ? "LIMIT $maxrecords" : '';
798
799     $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
800     $limit .= " OFFSET $offset" if $offset;
801
802   }
803
804   my $count_sth = dbh->prepare($opt{'count_query'})
805     or die "Error preparing $opt{'count_query'}: ". dbh->errstr;
806   $count_sth->execute
807     or die "Error executing $opt{'count_query'}: ". $count_sth->errstr;
808   $count_arrayref = $count_sth->fetchrow_arrayref;
809   $total = $count_arrayref->[0];
810
811 }
812
813 # run the query
814
815 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
816 my $rows;
817 if ( ref($opt{query}) ) {
818
819   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
820     #%search = ( 'disabled' => '' );
821     $opt{'query'}->{'hashref'}->{'disabled'} = '';
822     $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
823   }
824
825   #eval "use FS::$opt{'query'};";
826   $rows = [ qsearch({
827     'select'    => $opt{'query'}->{'select'},
828     'table'     => $opt{'query'}->{'table'}, 
829     'addl_from' => (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : ''),
830     'hashref'   => $opt{'query'}->{'hashref'} || {}, 
831     'extra_sql' => $opt{'query'}->{'extra_sql'},
832     'order_by'  => $opt{'query'}->{'order_by'}. " $limit",
833   }) ];
834 } else {
835   my $sth = dbh->prepare("$opt{'query'} $limit")
836     or die "Error preparing $opt{'query'}: ". dbh->errstr;
837   $sth->execute
838     or die "Error executing $opt{'query'}: ". $sth->errstr;
839
840   #can get # of rows without fetching them all?
841   $rows = $sth->fetchall_arrayref;
842
843   $header ||= $sth->{NAME};
844 }
845
846 </%init>