This commit was generated by cvs2svn to compensate for changes in r6252,
[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 %     }
323 %
324 %     if ( $total || $opt{'disableable'} ) { #hmm... and there *are* ones to show??
325
326         <TABLE>
327           <TR>
328
329             <TD VALIGN="bottom">
330
331               <FORM>
332
333                 <% $total %> total <% $opt{'name'} %>
334
335 %               if ( $confmax && $total > $confmax && $type ne 'html-print' ) {
336 %                 $cgi->delete('maxrecords');
337 %                 $cgi->param('_dummy', 1);
338
339 %#                 ( show <SELECT NAME="maxrecords" onChange="this.form.submit();">
340                   ( show <SELECT NAME="maxrecords" onChange="window.location = '<% $cgi->self_url %>;maxrecords=' + this.options[this.selectedIndex].value;">
341
342 %                   foreach my $max ( map { $_ * $confmax } qw( 1 5 10 25 ) ) {
343                   <OPTION VALUE="<% $max %>" <% ( $maxrecords == $max ) ? 'SELECTED' : '' %>><% $max %></OPTION>
344 %                   }
345
346                   </SELECT> per page )
347
348 %                 $cgi->param('maxrecords', $maxrecords);
349 %               }
350
351 %               if ( defined($opt{'html_posttotal'}) && $type ne 'html-print' ) {
352                     <% ref($opt{'html_posttotal'})
353                          ? &{$opt{'html_posttotal'}}()
354                          : $opt{'html_posttotal'}
355                     %>
356 %               }
357                 <BR>
358
359 %               if ( $opt{'count_addl'} ) { 
360 %                 my $n=0;
361 %                 foreach my $count ( @{$opt{'count_addl'}} ) { 
362 %                   my $data = $count_arrayref->[++$n];
363 %                   if ( ref($count) ) {
364                       <% &{ $count }( $data ) %>
365 %                   } else {
366                       <% sprintf( $count, $data ) %><BR>
367 %                   }
368 %                 } 
369 %               } 
370               </FORM>
371
372             </TD>
373
374 %           unless ( $opt{'disable_download'} || $type eq 'html-print' ) { 
375
376               <TD ALIGN="right">
377
378                 Download full results<BR>
379
380 %               $cgi->param('_type', "$xlsname.xls" ); 
381                 as <A HREF="<% $cgi->self_url %>">Excel spreadsheet</A><BR>
382
383 %               $cgi->param('_type', 'csv'); 
384                 as <A HREF="<% $cgi->self_url %>">CSV file</A><BR>
385
386 %               $cgi->param('_type', 'html-print'); 
387                 as <A HREF="<% $cgi->self_url %>">printable copy</A>
388
389               <% $opt{'extra_choices_callback'}
390                  ? &{$opt{'extra_choices_callback'}}($cgi->query_string)
391                  : ''
392               %>
393
394               </TD>
395 %             $cgi->param('_type', "html" ); 
396 %           } 
397
398           </TR>
399           <TR>
400             <TD COLSPAN=2>
401
402 %             my $pager = '';
403 %             unless ( $type eq 'html_print' ) {
404
405                 <% $pager = include( '/elements/pager.html',
406                                        'offset'     => $offset,
407                                        'num_rows'   => scalar(@$rows),
408                                        'total'      => $total,
409                                        'maxrecords' => $maxrecords,
410                                    )
411                 %>
412
413                 <% defined($opt{'html_form'}) 
414                      ? ( ref($opt{'html_form'})
415                            ? &{$opt{'html_form'}}()
416                            : $opt{'html_form'}
417                        )
418                      : ''
419                 %>
420
421 %             }
422
423               <% include('/elements/table-grid.html') %>
424
425                 <TR>
426 %                 my $h2 = 0;
427 %                 foreach my $header ( @{ $opt{header} } ) { 
428 %                   my $label = ref($header) ? $header->{label} : $header;
429 %                   my $rowspan = 1;
430 %                   my $style = '';
431 %                   if ( $opt{header2} ) {
432 %                     if ( !length($opt{header2}->[$h2]) ) {
433 %                       $rowspan = 2;
434 %                       splice @{ $opt{header2} }, $h2, 1;
435 %                     } else {
436 %                       $h2++;
437 %                       $style = 'STYLE="border-bottom: none"'
438 %                     }
439 %                   }
440                     <TH CLASS   = "grid"
441                         BGCOLOR = "#cccccc"
442                         ROWSPAN = "<% $rowspan %>"
443                         <% $style %>
444
445                     >
446                       <% $label %>
447                     </TH>
448 %                 } 
449                 </TR>
450
451 %               if ( $opt{header2} ) {
452                   <TR>
453 %                   foreach my $header ( @{ $opt{header2} } ) { 
454 %                     my $label = ref($header) ? $header->{label} : $header;
455                       <TH CLASS="grid" BGCOLOR="#cccccc">
456                         <FONT SIZE="-1"><% $label %></FONT>
457                       </TH>
458 %                   } 
459                   </TR>
460 %               }
461
462 %               my $bgcolor1 = '#eeeeee';
463 %               my $bgcolor2 = '#ffffff';
464 %               my $bgcolor;
465 %
466 %               foreach my $row ( @$rows ) {
467 %
468 %                 if ( $bgcolor eq $bgcolor1 ) {
469 %                   $bgcolor = $bgcolor2;
470 %                 } else {
471 %                   $bgcolor = $bgcolor1;
472 %                 }
473
474                   <TR>
475
476 %                   if ( $opt{'fields'} ) {
477 %
478 %                     my $links    = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
479 %                     my $onclicks = $opt{'link_onclicks'} ? [ @{$opt{'link_onclicks'}} ] : [];
480 %                     my $aligns   = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
481 %                     my $colors   = $opt{'color'} ? [ @{$opt{'color'}} ] : [];
482 %                     my $sizes    = $opt{'size'}  ? [ @{$opt{'size'}}  ] : [];
483 %                     my $styles   = $opt{'style'} ? [ @{$opt{'style'}} ] : [];
484 %                     my $cstyles  = $opt{'cell_style'} ? [ @{$opt{'cell_style'}} ] : [];
485 %
486 %                     foreach my $field (
487 %
488 %                       map {
489 %                             if ( ref($_) eq 'ARRAY' ) {
490 %
491 %                               my $tableref = $_;
492 %
493 %                               '<TABLE CLASS="inv" CELLSPACING=0 CELLPADDING=0 WIDTH="100%">'.
494 %
495 %                               join('', map {
496 %
497 %                                 my $rowref = $_;
498 %
499 %                                 '<tr>'.
500 %
501 %                                 join('', map {
502 %
503 %                                   my $e = $_;
504 %
505 %                                   '<TD '.
506 %                                     join(' ', map {
507 %                                       uc($_).'="'. $e->{$_}. '"';
508 %                                     }
509 %                                     grep exists($e->{$_}),
510 %                                          qw( align bgcolor colspan rowspan
511 %                                              style valign width )
512 %                                     ).
513 %                                   '>'.
514 %
515 %                                   ( $e->{'link'}
516 %                                       ? '<A HREF="'. $e->{'link'}. '">'
517 %                                       : ''
518 %                                   ).
519 %                                   ( $e->{'size'}
520 %                                      ? '<FONT SIZE="'.uc($e->{'size'}).'">'
521 %                                      : ''
522 %                                   ).
523 %                                   ( $e->{'data_style'}
524 %                                       ? '<'. uc($e->{'data_style'}). '>'
525 %                                       : ''
526 %                                   ).
527 %                                   $e->{'data'}.
528 %                                   ( $e->{'data_style'}
529 %                                       ? '</'. uc($e->{'data_style'}). '>'
530 %                                       : ''
531 %                                   ).
532 %                                   ( $e->{'size'} ? '</FONT>' : '' ).
533 %                                   ( $e->{'link'} ? '</A>'    : '' ).
534 %                                   '</td>';
535 %
536 %                                 } @$rowref ).
537 %
538 %                                 '</tr>';
539 %                               } @$tableref ).
540 %
541 %                               '</table>';
542 %
543 %                             } else {
544 %                               $_;
545 %                             }
546 %                           }
547 %
548 %                       map {
549 %                             if ( ref($_) eq 'CODE' ) {
550 %                               &{$_}($row);
551 %                             } else {
552 %                               $row->$_();
553 %                             }
554 %                           }
555 %                       @{$opt{'fields'}}
556 %
557 %                     ) {
558 %
559 %                       my $class = ( $field =~ /^<TABLE/i ) ? 'inv' : 'grid';
560 %
561 %                       my $align = $aligns ? shift @$aligns : '';
562 %                       $align = " ALIGN=$align" if $align;
563 %
564 %                       my $a = '';
565 %                       if ( $links ) {
566 %                         my $link = shift @$links;
567 %                         $link = &{$link}($row)
568 %                           if ref($link) eq 'CODE';
569 %
570 %                         my $onclick = shift @$onclicks;
571 %                         $onclick = &{$onclick}($row)
572 %                           if ref($onclick) eq 'CODE';
573 %                         $onclick = qq( onClick="$onclick") if $onclick;
574 %
575 %                         if ( $link ) {
576 %                           my( $url, $method ) = @{$link};
577 %                           if ( ref($method) eq 'CODE' ) {
578 %                             $a = $url. &{$method}($row);
579 %                           } else {
580 %                             $a = $url. $row->$method();
581 %                           }
582 %                           $a = qq(<A HREF="$a"$onclick>);
583 %                         }
584 %                       }
585 %
586 %                       my $font = '';
587 %                       my $color = shift @$colors;
588 %                       $color = &{$color}($row) if ref($color) eq 'CODE';
589 %                       my $size = shift @$sizes;
590 %                       $size = &{$size}($row) if ref($size) eq 'CODE';
591 %                       if ( $color || $size ) {
592 %                         $font = '<FONT '.
593 %                                 ( $color ? "COLOR=#$color "   : '' ).
594 %                                 ( $size  ? qq(SIZE="$size" )  : '' ).
595 %                                 '>';
596 %                       }
597 %
598 %                       my($s, $es) = ( '', '' );
599 %                       my $style = shift @$styles;
600 %                       $style = &{$style}($row) if ref($style) eq 'CODE';
601 %                       if ( $style ) {
602 %                         $s = join( '', map "<$_>", split('', $style) );
603 %                         $es = join( '', map "</$_>", split('', $style) );
604 %                       }
605 %
606 %                       my $cstyle = shift @$cstyles;
607 %                       $cstyle = &{$cstyle}($row) if ref($cstyle) eq 'CODE';
608 %                       $cstyle = qq(STYLE="$cstyle")
609 %                         if $cstyle;
610
611                         <TD CLASS="<% $class %>" BGCOLOR="<% $bgcolor %>" <% $align %> <% $cstyle %>><% $font %><% $a %><% $s %><% $field %><% $es %><% $a ? '</A>' : '' %><% $font ? '</FONT>' : '' %></TD>
612
613 %                     } 
614 %
615 %                   } else { 
616 %
617 %                     foreach ( @$row ) { 
618                         <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $_ %></TD>
619 %                     }
620 %
621 %                   }
622
623                   </TR>
624
625 %               } 
626
627 %               if ( $opt{'footer'} ) { 
628
629                   <TR>
630
631 %                   foreach my $footer ( @{ $opt{'footer'} } ) { 
632                       <TD CLASS="grid" BGCOLOR="#dddddd" STYLE="border-top: dashed 1px black;"><i><% $footer %></i></TD>
633 %                   } 
634
635                   </TR>
636 %               } 
637             
638               </TABLE>
639
640               <% $pager %>
641   
642             </TD>
643           </TR>
644         </TABLE>
645 %     }
646
647 %     if ( $type eq 'html-print' ) {
648
649         </BODY></HTML>
650       
651 %     } else {
652
653         <% defined($opt{'html_foot'}) 
654               ? ( ref($opt{'html_foot'})
655                     ? &{$opt{'html_foot'}}()
656                     : $opt{'html_foot'}
657                 )
658               : ''
659         %>
660
661         <% include( '/elements/footer.html' ) %>
662
663 %     }
664
665 %   } 
666 %
667 % } 
668 <%init>
669
670 my(%opt) = @_;
671 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
672
673 my $curuser = $FS::CurrentUser::CurrentUser;
674
675 my %align = (
676   'l' => 'left',
677   'r' => 'right',
678   'c' => 'center',
679   ' ' => '',
680   '.' => '',
681 );
682 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
683   unless !$opt{align} || ref($opt{align});
684
685 if ( $opt{'agent_virt'} ) {
686
687   my $agentnums_sql = $curuser->agentnums_sql(
688                         'null_right' => $opt{'agent_null_right'}
689                       );
690
691   $opt{'query'}{'extra_sql'} .=
692     ( $opt{'query'}       =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
693     $agentnums_sql;
694   $opt{'count_query'} .=
695     ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
696     $agentnums_sql;
697
698   if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
699        and scalar($curuser->agentnums) > 1           ) {
700     #false laziness w/statuspos above
701     my $pos = $opt{'agent_pos'};
702
703     foreach my $att (qw( align style color size )) {
704       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
705     }
706
707     splice @{ $opt{'header'} }, $pos, 0, 'Agent'; 
708     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
709     splice @{ $opt{'style'}  }, $pos, 0, ''; 
710     splice @{ $opt{'size'}   }, $pos, 0, ''; 
711     splice @{ $opt{'fields'} }, $pos, 0,
712       sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
713     splice @{ $opt{'color'}  }, $pos, 0, '';
714     splice @{ $opt{'links'}  }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
715       if $opt{'links'};
716     splice @{ $opt{'link_onclicks'}  }, $pos, 0, ''
717       if $opt{'link_onclicks'};
718
719   }
720
721 }
722
723 if ( $opt{'disableable'} ) {
724
725   unless ( $cgi->param('showdisabled') ) { #modify searches
726
727     $opt{'query'}{'hashref'}{'disabled'} = '';
728     $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
729
730     $opt{'count_query'} .=
731       ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
732       "( disabled = '' OR disabled IS NULL )";
733
734   } elsif (    $opt{'disabled_statuspos'}
735             || $opt{'disabled_statuspos'} eq '0' ) { #add status column
736
737     my $pos = $opt{'disabled_statuspos'};
738
739     foreach my $att (qw( align style color size )) {
740       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
741     }
742
743     splice @{ $opt{'header'} }, $pos, 0, 'Status'; 
744     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
745     splice @{ $opt{'style'}  }, $pos, 0, 'b'; 
746     splice @{ $opt{'size'}   }, $pos, 0, ''; 
747     splice @{ $opt{'fields'} }, $pos, 0,
748       sub { shift->disabled ? 'DISABLED' : 'Active'; };
749     splice @{ $opt{'color'}  }, $pos, 0,
750       sub { shift->disabled ? 'FF0000'   : '00CC00'; };
751     splice @{ $opt{'links'}  }, $pos, 0, ''
752       if $opt{'links'};
753     splice @{ $opt{'link_onlicks'}  }, $pos, 0, ''
754       if $opt{'link_onlicks'};
755   }
756
757   #add show/hide disabled links
758   my $items = $opt{'name'} || PL($opt{'name_singular'});
759   if ( $cgi->param('showdisabled') ) {
760     $cgi->param('showdisabled', 0);
761     $opt{'html_posttotal'} .=
762       '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!;
763     $cgi->param('showdisabled', 1);
764   } else {
765     $cgi->param('showdisabled', 1);
766     $opt{'html_posttotal'} .=
767       '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!;
768     $cgi->param('showdisabled', 0);
769   }
770
771 }
772
773 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|html(-print)?)$/
774            ? $1 : 'html';
775
776 my $limit = '';
777 my($confmax, $maxrecords, $total, $offset, $count_arrayref);
778
779 unless ( $type =~ /^(csv|\w*\.xls)$/ ) {
780
781   unless (exists($opt{count_query}) && length($opt{count_query})) {
782     ( $opt{count_query} = $opt{query} ) =~
783       s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
784   }
785
786   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
787     $opt{count_query} .=
788       ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
789       "( disabled = '' OR disabled IS NULL )";
790   }
791
792   unless ( $type eq 'html-print' ) {
793
794     #setup some pagination things if we're in html mode
795
796     my $conf = new FS::Conf;
797     $confmax = $conf->config('maxsearchrecordsperpage');
798     if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
799       $maxrecords = $1;
800     } else {
801       $maxrecords ||= $confmax;
802     }
803
804     $limit = $maxrecords ? "LIMIT $maxrecords" : '';
805
806     $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
807     $limit .= " OFFSET $offset" if $offset;
808
809   }
810
811   my $count_sth = dbh->prepare($opt{'count_query'})
812     or die "Error preparing $opt{'count_query'}: ". dbh->errstr;
813   $count_sth->execute
814     or die "Error executing $opt{'count_query'}: ". $count_sth->errstr;
815   $count_arrayref = $count_sth->fetchrow_arrayref;
816   $total = $count_arrayref->[0];
817
818 }
819
820 # run the query
821
822 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
823 my $rows;
824 if ( ref($opt{query}) ) {
825
826   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
827     #%search = ( 'disabled' => '' );
828     $opt{'query'}->{'hashref'}->{'disabled'} = '';
829     $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
830   }
831
832   #eval "use FS::$opt{'query'};";
833   $rows = [ qsearch({
834     'select'    => $opt{'query'}->{'select'},
835     'table'     => $opt{'query'}->{'table'}, 
836     'addl_from' => (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : ''),
837     'hashref'   => $opt{'query'}->{'hashref'} || {}, 
838     'extra_sql' => $opt{'query'}->{'extra_sql'},
839     'order_by'  => $opt{'query'}->{'order_by'}. " $limit",
840   }) ];
841 } else {
842   my $sth = dbh->prepare("$opt{'query'} $limit")
843     or die "Error preparing $opt{'query'}: ". dbh->errstr;
844   $sth->execute
845     or die "Error executing $opt{'query'}: ". $sth->errstr;
846
847   #can get # of rows without fetching them all?
848   $rows = $sth->fetchall_arrayref;
849
850   $header ||= $sth->{NAME};
851 }
852
853 </%init>