This commit was generated by cvs2svn to compensate for changes in r9232,
[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 or arrayref
20     #of qsearch hashrefs for a union of qsearches
21     'query'       => {
22                        'table'     => 'tablename',
23                        #everything else is optional...
24                        'hashref'   => { 'field' => 'value',
25                                         'field' => { 'op'    => '<',
26                                                      'value' => '54',
27                                                    },
28                                       },
29                        'select'    => '*',
30                        'addl_from' => '', #'LEFT JOIN othertable USING ( key )',
31                        'extra_sql' => '', #'AND otherstuff', #'WHERE onlystuff',
32                        'order_by'  => 'ORDER BY something',
33    
34                      },
35                      # "select * from tablename";
36    
37     #required unless 'query' is an SQL query string (shouldn't be...)
38     'count_query' => 'SELECT COUNT(*) FROM tablename',
39
40     ###
41     # recommended / common
42     ###
43
44     #listref of column labels, <TH>
45     #recommended unless 'query' is an SQL query string
46     # (if not specified the database column names will be used)
47     'header'      => [ '#',
48                        'Item',
49                        { 'label' => 'Another Item',
50                          
51                        },
52                      ],
53
54     #listref - each item is a literal column name (or method) or coderef
55     #if not specified all columns will be shown
56     'fields'      => [
57                        'column',
58                        sub { my $row = shift; $row->column; },
59                      ],
60
61     #redirect if there's only one item...
62     # listref of URL base and column name (or method)
63     # or a coderef that returns the same
64     'redirect' => sub { my( $record, $cgi ) = @_;
65                         [ popurl(2).'view/item.html', 'primary_key' ];
66                       },
67
68     #redirect if there's no items
69     # scalar URL or a coderef that returns a URL
70     'redirect_empty' => sub { my( $cgi ) = @_;
71                               popurl(2).'view/item.html';
72                             },
73    
74     ###
75     # optional
76     ###
77    
78     # some HTML callbacks...
79     'menubar'          => '', #menubar arrayref
80     'html_init'        => '', #after the header/menubar and before the pager
81     'html_form'        => '', #after the pager, right before the results
82                               # (only shown if there are results)
83                               # (use this for any form-opening tag rather than
84                               #  html_init, to avoid a nested form)
85     'html_foot'        => '', #at the bottom
86     'html_posttotal'   => '', #at the bottom
87                               # (these three can be strings or coderefs)
88     
89     'count_addl' => [], #additional count fields listref of sprintf strings or coderefs
90                         # [ $money_char.'%.2f total paid', ],
91    
92     #second (smaller) header line, currently only for HTML
93     'header2      => [ '#',
94                        'Item',
95                        { 'label' => 'Another Item',
96                          
97                        },
98                      ],
99
100     #listref of column footers
101     'footer'      => [],
102     
103     #disabling things
104     'disable_download'  => '', # set true to hide the CSV/Excel download links
105     'disable_total'     => '', # set true to hide the total"
106     'disable_maxselect' => '', # set true to disable record/page selection
107     'disable_nonefound' => '', # set true to disable the "No matching Xs found"
108                                # message
109    
110     #handling "disabled" fields in the records
111     'disableable' => 1,  # set set to 1 (or column position for "disabled"
112                          # status col) to enable if this table has a "disabled"
113                          # field, to hide disabled records & have
114                          # "show disabled/hide disabled" links
115                          #(can't be used with a literal query)
116     'disabled_statuspos' => 3, #optional position (starting from 0) to insert
117                                #a Status column when showing disabled records
118                                #(query needs to be a qsearch hashref and
119                                # header & fields need to be defined)
120
121     #handling agent virtualization
122     'agent_virt'            => 1, # set true if this search should be
123                                   # agent-virtualized
124     'agent_null_right'      => 'Access Right', # optional right to view global
125                                                # records
126     'agent_null_right_link' => 'Access Right'  # optional right to link to
127                                                # global records; defaults to
128                                                # same as agent_null_right
129     'agent_pos'             => 3, # optional position (starting from 0) to
130                                   # insert an Agent column (query needs to be a
131                                   # qsearch hashref and header & fields need to
132                                   # be defined)
133
134     # link & display properties for fields
135    
136     #listref - each item is the empty string,
137     #          or a listref of link and method name to append,
138     #          or a listref of link and coderef to run and append
139     #          or a coderef that returns such a listref
140     'links'       => [],`
141
142     #listref - each item is the empty string,
143     #          or a string onClick handler for the corresponding link
144     #          or a coderef that returns string onClick handler
145     'link_onclicks' => [],
146
147     #one letter for each column, left/right/center/none
148     # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
149     'align'       => 'lrc.',
150    
151     #listrefs of ( scalars or coderefs )
152     # currently only HTML, maybe eventually Excel too
153     'color'       => [],
154     'size'        => [],
155     'style'       => [], #<B> or <I>, etc.
156     'cell_style'  => [], #STYLE= attribute of TR, very HTML-specific...
157
158     # Excel-specific listref of ( hashrefs or coderefs )
159     # each hashref: http://search.cpan.org/dist/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm#Format_methods_and_Format_properties
160     'xls_format' => => [],
161     
162   );
163
164 </%doc>
165 % if ( $type eq 'csv' ) {
166 %
167 <% include('search-csv.html',  header=>$header, rows=>$rows, opt=>\%opt ) %>
168 %
169 % #} elsif ( $type eq 'excel' ) {
170 % } elsif ( $type =~ /\.xls$/ ) {
171 %
172 <% include('search-xls.html',  header=>$header, rows=>$rows, opt=>\%opt ) %>
173 %
174 % } else { # regular HTML
175 %
176 <% include('search-html.html',
177              type           => $type,
178              header         => $header,
179              rows           => $rows,
180              link_agentnums => \@link_agentnums,
181              null_link      => $null_link,
182              confmax        => $confmax,
183              maxrecords     => $maxrecords,
184              offset         => $offset,
185              opt            => \%opt
186           )
187 %>
188 %
189 % } 
190 <%init>
191
192 my(%opt) = @_;
193 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
194
195 my $curuser = $FS::CurrentUser::CurrentUser;
196
197 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|select|html(-print)?)$/
198            ? $1 : 'html' ;
199
200 my %align = (
201   'l' => 'left',
202   'r' => 'right',
203   'c' => 'center',
204   ' ' => '',
205   '.' => '',
206 );
207 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
208   unless !$opt{align} || ref($opt{align});
209
210 if($type =~ /csv|xls/) {
211   my $h = $opt{'header'};
212   my @del;
213   my $i = 0;
214   do {
215     if( ref($h->[$i]) and exists($h->[$i]->{'nodownload'}) ) {
216       splice(@{$opt{$_}}, $i, 1) foreach
217         qw(header footer fields links link_onclicks
218            align color size style cell_style xls_format);
219     }
220     else {
221       $i++;
222     }
223   } while ( exists($h->[$i]) );
224 }
225
226 $opt{disable_download} = 0
227   if $opt{disable_download} && $curuser->access_right('Configuration download');
228
229 my @link_agentnums = ();
230 my $null_link = '';
231 if ( $opt{'agent_virt'} ) {
232
233   @link_agentnums = $curuser->agentnums;
234   $null_link = $curuser->access_right(    $opt{'agent_null_right_link'}
235                                        || $opt{'agent_null_right'}      );
236
237   my $agentnums_sql = $curuser->agentnums_sql(
238                         'null_right' => $opt{'agent_null_right'}
239                       );
240
241   $opt{'query'}{'extra_sql'} .=
242     ( $opt{'query'}{'extra_sql'} =~ /WHERE/i || keys %{$opt{'query'}{'hashref'}}
243       ? ' AND '
244       : ' WHERE ' ). $agentnums_sql;
245
246   $opt{'count_query'} .=
247     ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).  $agentnums_sql;
248
249   if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
250        and scalar($curuser->agentnums) > 1           ) {
251     #false laziness w/statuspos above
252     my $pos = $opt{'agent_pos'};
253
254     foreach my $att (qw( align color size style cell_style xls_format )) {
255       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
256     }
257
258     splice @{ $opt{'header'} }, $pos, 0, 'Agent'; 
259     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
260     splice @{ $opt{'style'}  }, $pos, 0, ''; 
261     splice @{ $opt{'size'}   }, $pos, 0, ''; 
262     splice @{ $opt{'fields'} }, $pos, 0,
263       sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
264     splice @{ $opt{'color'}  }, $pos, 0, '';
265     splice @{ $opt{'links'}  }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
266       if $opt{'links'};
267     splice @{ $opt{'link_onclicks'}  }, $pos, 0, ''
268       if $opt{'link_onclicks'};
269
270   }
271
272 }
273
274 if ( $opt{'disableable'} ) {
275
276   unless ( $cgi->param('showdisabled') ) { #modify searches
277
278     $opt{'query'}{'hashref'}{'disabled'} = '';
279     $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
280
281     $opt{'count_query'} .=
282       ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
283       "( disabled = '' OR disabled IS NULL )";
284
285   } elsif (    $opt{'disabled_statuspos'}
286             || $opt{'disabled_statuspos'} eq '0' ) { #add status column
287
288     my $pos = $opt{'disabled_statuspos'};
289
290     foreach my $att (qw( align style color size )) {
291       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
292     }
293
294     splice @{ $opt{'header'} }, $pos, 0, 'Status'; 
295     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
296     splice @{ $opt{'style'}  }, $pos, 0, 'b'; 
297     splice @{ $opt{'size'}   }, $pos, 0, ''; 
298     splice @{ $opt{'fields'} }, $pos, 0,
299       sub { shift->disabled ? 'DISABLED' : 'Active'; };
300     splice @{ $opt{'color'}  }, $pos, 0,
301       sub { shift->disabled ? 'FF0000'   : '00CC00'; };
302     splice @{ $opt{'links'}  }, $pos, 0, ''
303       if $opt{'links'};
304     splice @{ $opt{'link_onlicks'}  }, $pos, 0, ''
305       if $opt{'link_onlicks'};
306   }
307
308   #add show/hide disabled links
309   my $items = $opt{'name'} || PL($opt{'name_singular'});
310   if ( $cgi->param('showdisabled') ) {
311     $cgi->param('showdisabled', 0);
312     $opt{'html_posttotal'} .=
313       '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!; #"
314     $cgi->param('showdisabled', 1);
315   } else {
316     $cgi->param('showdisabled', 1);
317     $opt{'html_posttotal'} .=
318       '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!; #"
319     $cgi->param('showdisabled', 0);
320   }
321
322 }
323
324 my $limit = '';
325 my($confmax, $maxrecords, $offset );
326
327 if ( !$type =~ /^(csv|\w*.xls)$/) {
328 # html mode
329   unless (exists($opt{count_query}) && length($opt{count_query})) {
330     ( $opt{count_query} = $opt{query} ) =~
331       s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
332   }
333
334   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
335     $opt{count_query} .=
336       ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
337       "( disabled = '' OR disabled IS NULL )";
338   }
339
340   unless ( $type eq 'html-print' ) {
341
342     #setup some pagination things if we're in html mode
343
344     my $conf = new FS::Conf;
345     $confmax = $conf->config('maxsearchrecordsperpage');
346     if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
347       $maxrecords = $1;
348     } else {
349       $maxrecords ||= $confmax;
350     }
351
352     $limit = $maxrecords ? "LIMIT $maxrecords" : '';
353
354     $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
355     $limit .= " OFFSET $offset" if $offset;
356
357   }
358
359 }
360
361 # run the query
362
363 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
364 my $rows;
365 if ( ref($opt{query}) ) {
366
367   my @query;
368   if (ref($opt{query}) eq 'HASH') {
369     @query = ( $opt{query} );
370   } elsif (ref($opt{query}) eq 'ARRAY') {
371     @query = @{ $opt{query} };
372   } else {
373     die "invalid query reference";
374   }
375
376   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
377     #%search = ( 'disabled' => '' );
378     $opt{'query'}->{'hashref'}->{'disabled'} = '';
379     $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
380   }
381
382   #eval "use FS::$opt{'query'};";
383   my @param = qw( select table addl_from hashref extra_sql order_by );
384   $rows = [ qsearch( [ map { my $query = $_;
385                              ({ map { $_ => $query->{$_} } @param });
386                            }
387                        @query
388                      ],
389                      'order_by' => $opt{order_by}. " ". $limit,
390                    )
391           ]; 
392 } else {
393   my $sth = dbh->prepare("$opt{'query'} $limit")
394     or die "Error preparing $opt{'query'}: ". dbh->errstr;
395   $sth->execute
396     or die "Error executing $opt{'query'}: ". $sth->errstr;
397
398   #can get # of rows without fetching them all?
399   $rows = $sth->fetchall_arrayref;
400
401   $header ||= $sth->{NAME};
402 }
403
404 </%init>