agent virt inventory, RT#7010
[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'            => 1, # set true to view global records always
125     'agent_null_right'      => 'Access Right', # optional right to view global
126                                                # records
127     'agent_null_right_link' => 'Access Right'  # optional right to link to
128                                                # global records; defaults to
129                                                # same as agent_null_right
130     'agent_pos'             => 3, # optional position (starting from 0) to
131                                   # insert an Agent column (query needs to be a
132                                   # qsearch hashref and header & fields need to
133                                   # be defined)
134
135     # link & display properties for fields
136    
137     #listref - each item is the empty string,
138     #          or a listref of link and method name to append,
139     #          or a listref of link and coderef to run and append
140     #          or a coderef that returns such a listref
141     'links'       => [],`
142
143     #listref - each item is the empty string,
144     #          or a string onClick handler for the corresponding link
145     #          or a coderef that returns string onClick handler
146     'link_onclicks' => [],
147
148     #one letter for each column, left/right/center/none
149     # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
150     'align'       => 'lrc.',
151    
152     #listrefs of ( scalars or coderefs )
153     # currently only HTML, maybe eventually Excel too
154     'color'       => [],
155     'size'        => [],
156     'style'       => [], #<B> or <I>, etc.
157     'cell_style'  => [], #STYLE= attribute of TR, very HTML-specific...
158
159     # Excel-specific listref of ( hashrefs or coderefs )
160     # each hashref: http://search.cpan.org/dist/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm#Format_methods_and_Format_properties
161     'xls_format' => => [],
162     
163   )
164
165 </%doc>
166 % if ( $type eq 'csv' ) {
167 %
168 <% include('search-csv.html',  header=>$header, rows=>$rows, opt=>\%opt ) %>
169 %
170 % #} elsif ( $type eq 'excel' ) {
171 % } elsif ( $type =~ /\.xls$/ ) {
172 %
173 <% include('search-xls.html',  header=>$header, rows=>$rows, opt=>\%opt ) %>
174 %
175 % } else { # regular HTML
176 %
177 <% include('search-html.html',
178              type           => $type,
179              header         => $header,
180              rows           => $rows,
181              link_agentnums => \@link_agentnums,
182              null_link      => $null_link,
183              confmax        => $confmax,
184              maxrecords     => $maxrecords,
185              offset         => $offset,
186              opt            => \%opt
187           )
188 %>
189 %
190 % } 
191 <%init>
192
193 my(%opt) = @_;
194 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
195
196 my $curuser = $FS::CurrentUser::CurrentUser;
197
198 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|select|html(-print)?)$/
199            ? $1 : 'html' ;
200
201 my %align = (
202   'l' => 'left',
203   'r' => 'right',
204   'c' => 'center',
205   ' ' => '',
206   '.' => '',
207 );
208 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
209   unless !$opt{align} || ref($opt{align});
210
211 if($type =~ /csv|xls/) {
212   my $h = $opt{'header'};
213   my @del;
214   my $i = 0;
215   do {
216     if( ref($h->[$i]) and exists($h->[$i]->{'nodownload'}) ) {
217       splice(@{$opt{$_}}, $i, 1) foreach
218         qw(header footer fields links link_onclicks
219            align color size style cell_style xls_format);
220     }
221     else {
222       $i++;
223     }
224   } while ( exists($h->[$i]) );
225 }
226
227 $opt{disable_download} = 0
228   if $opt{disable_download} && $curuser->access_right('Configuration download');
229
230 my @link_agentnums = ();
231 my $null_link = '';
232 if ( $opt{'agent_virt'} ) {
233
234   @link_agentnums = $curuser->agentnums;
235   $null_link = $curuser->access_right(    $opt{'agent_null_right_link'}
236                                        || $opt{'agent_null_right'}      );
237
238   my $agentnums_sql = $curuser->agentnums_sql(
239                         'null'       => $opt{'agent_null'},
240                         'null_right' => $opt{'agent_null_right'},
241                         'table'      => $opt{'query'}{'table'},
242                       );
243
244   $opt{'query'}{'extra_sql'} .=
245     ( $opt{'query'}{'extra_sql'} =~ /WHERE/i || keys %{$opt{'query'}{'hashref'}}
246       ? ' AND '
247       : ' WHERE ' ). $agentnums_sql;
248
249   $opt{'count_query'} .=
250     ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).  $agentnums_sql;
251
252   if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
253        and scalar($curuser->agentnums) > 1           ) {
254     #false laziness w/statuspos above
255     my $pos = $opt{'agent_pos'};
256
257     foreach my $att (qw( align color size style cell_style xls_format )) {
258       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
259     }
260
261     splice @{ $opt{'header'} }, $pos, 0, 'Agent'; 
262     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
263     splice @{ $opt{'style'}  }, $pos, 0, ''; 
264     splice @{ $opt{'size'}   }, $pos, 0, ''; 
265     splice @{ $opt{'fields'} }, $pos, 0,
266       sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
267     splice @{ $opt{'color'}  }, $pos, 0, '';
268     splice @{ $opt{'links'}  }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
269       if $opt{'links'};
270     splice @{ $opt{'link_onclicks'}  }, $pos, 0, ''
271       if $opt{'link_onclicks'};
272
273   }
274
275 }
276
277 if ( $opt{'disableable'} ) {
278
279   unless ( $cgi->param('showdisabled') ) { #modify searches
280
281     $opt{'query'}{'hashref'}{'disabled'} = '';
282     $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
283
284     $opt{'count_query'} .=
285       ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
286       "( disabled = '' OR disabled IS NULL )";
287
288   } elsif (    $opt{'disabled_statuspos'}
289             || $opt{'disabled_statuspos'} eq '0' ) { #add status column
290
291     my $pos = $opt{'disabled_statuspos'};
292
293     foreach my $att (qw( align style color size )) {
294       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
295     }
296
297     splice @{ $opt{'header'} }, $pos, 0, 'Status'; 
298     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
299     splice @{ $opt{'style'}  }, $pos, 0, 'b'; 
300     splice @{ $opt{'size'}   }, $pos, 0, ''; 
301     splice @{ $opt{'fields'} }, $pos, 0,
302       sub { shift->disabled ? 'DISABLED' : 'Active'; };
303     splice @{ $opt{'color'}  }, $pos, 0,
304       sub { shift->disabled ? 'FF0000'   : '00CC00'; };
305     splice @{ $opt{'links'}  }, $pos, 0, ''
306       if $opt{'links'};
307     splice @{ $opt{'link_onlicks'}  }, $pos, 0, ''
308       if $opt{'link_onlicks'};
309   }
310
311   #add show/hide disabled links
312   my $items = $opt{'name'} || PL($opt{'name_singular'});
313   if ( $cgi->param('showdisabled') ) {
314     $cgi->param('showdisabled', 0);
315     $opt{'html_posttotal'} .=
316       '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!; #"
317     $cgi->param('showdisabled', 1);
318   } else {
319     $cgi->param('showdisabled', 1);
320     $opt{'html_posttotal'} .=
321       '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!; #"
322     $cgi->param('showdisabled', 0);
323   }
324
325 }
326
327 my $limit = '';
328 my($confmax, $maxrecords, $offset );
329
330 if ( !$type =~ /^(csv|\w*.xls)$/) {
331 # html mode
332   unless (exists($opt{count_query}) && length($opt{count_query})) {
333     ( $opt{count_query} = $opt{query} ) =~
334       s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
335   }
336
337   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
338     $opt{count_query} .=
339       ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
340       "( disabled = '' OR disabled IS NULL )";
341   }
342
343   unless ( $type eq 'html-print' ) {
344
345     #setup some pagination things if we're in html mode
346
347     my $conf = new FS::Conf;
348     $confmax = $conf->config('maxsearchrecordsperpage');
349     if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
350       $maxrecords = $1;
351     } else {
352       $maxrecords ||= $confmax;
353     }
354
355     $limit = $maxrecords ? "LIMIT $maxrecords" : '';
356
357     $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
358     $limit .= " OFFSET $offset" if $offset;
359
360   }
361
362 }
363
364 # run the query
365
366 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
367 my $rows;
368 if ( ref($opt{query}) ) {
369
370   my @query;
371   if (ref($opt{query}) eq 'HASH') {
372     @query = ( $opt{query} );
373   } elsif (ref($opt{query}) eq 'ARRAY') {
374     @query = @{ $opt{query} };
375   } else {
376     die "invalid query reference";
377   }
378
379   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
380     #%search = ( 'disabled' => '' );
381     $opt{'query'}->{'hashref'}->{'disabled'} = '';
382     $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
383   }
384
385   #eval "use FS::$opt{'query'};";
386   my @param = qw( select table addl_from hashref extra_sql order_by );
387   $rows = [ qsearch( [ map { my $query = $_;
388                              ({ map { $_ => $query->{$_} } @param });
389                            }
390                        @query
391                      ],
392                      'order_by' => $opt{order_by}. " ". $limit,
393                    )
394           ]; 
395 } else {
396   my $sth = dbh->prepare("$opt{'query'} $limit")
397     or die "Error preparing $opt{'query'}: ". dbh->errstr;
398   $sth->execute
399     or die "Error executing $opt{'query'}: ". $sth->errstr;
400
401   #can get # of rows without fetching them all?
402   $rows = $sth->fetchall_arrayref;
403
404   $header ||= $sth->{NAME};
405 }
406
407 </%init>