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