break down search.html into components, RT#5108
[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 <% include('search-csv.html',  header=>$header, rows=>$rows, opt=>\%opt ) %>
163 %
164 % #} elsif ( $type eq 'excel' ) {
165 % } elsif ( $type =~ /\.xls$/ ) {
166 %
167 <% include('search-xls.html',  header=>$header, rows=>$rows, opt=>\%opt ) %>
168 %
169 % } else { # regular HTML
170 %
171 <% include('search-html.html',
172              type           => $type,
173              header         => $header,
174              rows           => $rows,
175              link_agentnums => \@link_agentnums,
176              null_link      => $null_link,
177              confmax        => $confmax,
178              maxrecords     => $maxrecords,
179              offset         => $offset,
180              opt            => \%opt
181           )
182 %>
183 %
184 % } 
185 <%init>
186
187 my(%opt) = @_;
188 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
189
190 my $curuser = $FS::CurrentUser::CurrentUser;
191
192 my %align = (
193   'l' => 'left',
194   'r' => 'right',
195   'c' => 'center',
196   ' ' => '',
197   '.' => '',
198 );
199 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
200   unless !$opt{align} || ref($opt{align});
201
202 $opt{disable_download} = 0
203   if $opt{disable_download} && $curuser->access_right('Configuration download');
204
205 my @link_agentnums = ();
206 my $null_link = '';
207 if ( $opt{'agent_virt'} ) {
208
209   @link_agentnums = $curuser->agentnums;
210   $null_link = $curuser->access_right(    $opt{'agent_null_right_link'}
211                                        || $opt{'agent_null_right'}      );
212
213   my $agentnums_sql = $curuser->agentnums_sql(
214                         'null_right' => $opt{'agent_null_right'}
215                       );
216
217   $opt{'query'}{'extra_sql'} .=
218     ( $opt{'query'}{'extra_sql'} =~ /WHERE/i || keys %{$opt{'query'}{'hashref'}}
219       ? ' AND '
220       : ' WHERE ' ). $agentnums_sql;
221
222   $opt{'count_query'} .=
223     ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).  $agentnums_sql;
224
225   if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
226        and scalar($curuser->agentnums) > 1           ) {
227     #false laziness w/statuspos above
228     my $pos = $opt{'agent_pos'};
229
230     foreach my $att (qw( align style color size )) {
231       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
232     }
233
234     splice @{ $opt{'header'} }, $pos, 0, 'Agent'; 
235     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
236     splice @{ $opt{'style'}  }, $pos, 0, ''; 
237     splice @{ $opt{'size'}   }, $pos, 0, ''; 
238     splice @{ $opt{'fields'} }, $pos, 0,
239       sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
240     splice @{ $opt{'color'}  }, $pos, 0, '';
241     splice @{ $opt{'links'}  }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
242       if $opt{'links'};
243     splice @{ $opt{'link_onclicks'}  }, $pos, 0, ''
244       if $opt{'link_onclicks'};
245
246   }
247
248 }
249
250 if ( $opt{'disableable'} ) {
251
252   unless ( $cgi->param('showdisabled') ) { #modify searches
253
254     $opt{'query'}{'hashref'}{'disabled'} = '';
255     $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
256
257     $opt{'count_query'} .=
258       ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
259       "( disabled = '' OR disabled IS NULL )";
260
261   } elsif (    $opt{'disabled_statuspos'}
262             || $opt{'disabled_statuspos'} eq '0' ) { #add status column
263
264     my $pos = $opt{'disabled_statuspos'};
265
266     foreach my $att (qw( align style color size )) {
267       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
268     }
269
270     splice @{ $opt{'header'} }, $pos, 0, 'Status'; 
271     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
272     splice @{ $opt{'style'}  }, $pos, 0, 'b'; 
273     splice @{ $opt{'size'}   }, $pos, 0, ''; 
274     splice @{ $opt{'fields'} }, $pos, 0,
275       sub { shift->disabled ? 'DISABLED' : 'Active'; };
276     splice @{ $opt{'color'}  }, $pos, 0,
277       sub { shift->disabled ? 'FF0000'   : '00CC00'; };
278     splice @{ $opt{'links'}  }, $pos, 0, ''
279       if $opt{'links'};
280     splice @{ $opt{'link_onlicks'}  }, $pos, 0, ''
281       if $opt{'link_onlicks'};
282   }
283
284   #add show/hide disabled links
285   my $items = $opt{'name'} || PL($opt{'name_singular'});
286   if ( $cgi->param('showdisabled') ) {
287     $cgi->param('showdisabled', 0);
288     $opt{'html_posttotal'} .=
289       '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!;
290     $cgi->param('showdisabled', 1);
291   } else {
292     $cgi->param('showdisabled', 1);
293     $opt{'html_posttotal'} .=
294       '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!;
295     $cgi->param('showdisabled', 0);
296   }
297
298 }
299
300 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|select|html(-print)?)$/
301            ? $1 : 'html';
302
303 my $limit = '';
304 my($confmax, $maxrecords, $offset );
305
306 unless ( $type =~ /^(csv|\w*\.xls)$/ ) {
307
308   unless (exists($opt{count_query}) && length($opt{count_query})) {
309     ( $opt{count_query} = $opt{query} ) =~
310       s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
311   }
312
313   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
314     $opt{count_query} .=
315       ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
316       "( disabled = '' OR disabled IS NULL )";
317   }
318
319   unless ( $type eq 'html-print' ) {
320
321     #setup some pagination things if we're in html mode
322
323     my $conf = new FS::Conf;
324     $confmax = $conf->config('maxsearchrecordsperpage');
325     if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
326       $maxrecords = $1;
327     } else {
328       $maxrecords ||= $confmax;
329     }
330
331     $limit = $maxrecords ? "LIMIT $maxrecords" : '';
332
333     $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
334     $limit .= " OFFSET $offset" if $offset;
335
336   }
337
338 }
339
340 # run the query
341
342 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
343 my $rows;
344 if ( ref($opt{query}) ) {
345
346   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
347     #%search = ( 'disabled' => '' );
348     $opt{'query'}->{'hashref'}->{'disabled'} = '';
349     $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
350   }
351
352   #eval "use FS::$opt{'query'};";
353   $rows = [ qsearch({
354     'select'    => $opt{'query'}->{'select'},
355     'table'     => $opt{'query'}->{'table'}, 
356     'addl_from' => (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : ''),
357     'hashref'   => $opt{'query'}->{'hashref'} || {}, 
358     'extra_sql' => $opt{'query'}->{'extra_sql'},
359     'order_by'  => $opt{'query'}->{'order_by'}. " $limit",
360   }) ];
361 } else {
362   my $sth = dbh->prepare("$opt{'query'} $limit")
363     or die "Error preparing $opt{'query'}: ". dbh->errstr;
364   $sth->execute
365     or die "Error executing $opt{'query'}: ". $sth->errstr;
366
367   #can get # of rows without fetching them all?
368   $rows = $sth->fetchall_arrayref;
369
370   $header ||= $sth->{NAME};
371 }
372
373 </%init>