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