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