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