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