Merge branch 'patch-18' of https://github.com/gjones2/Freeside
[freeside.git] / httemplate / search / elements / search.html
1 <%doc>
2
3 Example:
4
5   <& 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     # sort, link & display properties for fields
136
137     'sort_fields' => [], #optional list of field names or SQL expressions for
138                          # sorts
139    
140     #listref - each item is the empty string,
141     #          or a listref of link and method name to append,
142     #          or a listref of link and coderef to run and append
143     #          or a coderef that returns such a listref
144     'links'       => [],`
145
146     #listref - each item is the empty string,
147     #          or a string onClick handler for the corresponding link
148     #          or a coderef that returns string onClick handler
149     'link_onclicks' => [],
150
151     #one letter for each column, left/right/center/none
152     # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
153     'align'       => 'lrc.',
154    
155     #listrefs of ( scalars or coderefs )
156     # currently only HTML, maybe eventually Excel too
157     'color'       => [],
158     'size'        => [],
159     'style'       => [], #<B> or <I>, etc.
160     'cell_style'  => [], #STYLE= attribute of TR, very HTML-specific...
161
162     # Excel-specific listref of ( hashrefs or coderefs )
163     # each hashref: http://search.cpan.org/dist/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm#Format_methods_and_Format_properties
164     'xls_format' => => [],
165    
166
167     # miscellany
168    'download_label' => 'Download this report',
169                         # defaults to 'Download full results' 
170    'link_field'     => 'pkgpart'
171                         # will create internal links for each row,
172                         # with the value of this field as the NAME attribute
173                         # If this is a coderef, will evaluate it, passing the
174                         # row as an argument, and use the result as the NAME.
175   &>
176
177 </%doc>
178 % if ( $type eq 'csv' ) {
179 %
180 <% include('search-csv.html',  header=>$header, rows=>$rows, opt=>\%opt ) %>
181 %
182 % } elsif ( $type =~ /\.xls$/ ) {
183 %
184 <& 'search-xls.html',  header=>$header, rows=>$rows, opt=>\%opt &>\
185 % # prevent the caller from polluting our output stream
186 % $m->abort;
187 %
188 % } elsif ( $type eq 'xml' ) {
189 %
190 <% include('search-xml.html',  rows=>$rows, opt=>\%opt ) %>
191 %
192 % } else {
193 %
194 <% include('search-html.html',
195              type           => $type,
196              header         => $header,
197              rows           => $rows,
198              link_agentnums => \@link_agentnums,
199              null_link      => $null_link,
200              confmax        => $confmax,
201              maxrecords     => $maxrecords,
202              offset         => $offset,
203              opt            => \%opt
204           )
205 %>
206 %
207 % } 
208 <%init>
209
210 my(%opt) = @_;
211 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
212
213 my $curuser = $FS::CurrentUser::CurrentUser;
214
215 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|xml|select|html(-print)?)$/
216            ? $1 : 'html' ;
217
218 if ( !$curuser->access_right('Download report data') ) {
219   $opt{'disable_download'} = 1;
220   $type = 'html';
221 }
222
223 my %align = (
224   'l' => 'left',
225   'r' => 'right',
226   'c' => 'center',
227   ' ' => '',
228   '.' => '',
229 );
230 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
231   unless !$opt{align} || ref($opt{align});
232
233 if($type =~ /csv|xls/) {
234   my $h = $opt{'header'};
235   my @del;
236   my $i = 0;
237   do {
238     if( ref($h->[$i]) and exists($h->[$i]->{'nodownload'}) ) {
239       splice(@{$opt{$_}}, $i, 1) foreach
240         qw(header footer fields links link_onclicks
241            align color size style cell_style xls_format);
242     }
243     else {
244       $i++;
245     }
246   } while ( exists($h->[$i]) );
247 }
248
249 # wtf?
250 $opt{disable_download} = 0
251   if $opt{disable_download} && $curuser->access_right('Configuration download');
252
253 $opt{disable_download} = 1
254   if $opt{really_disable_download};
255
256 my @link_agentnums = ();
257 my $null_link = '';
258 if ( $opt{'agent_virt'} ) {
259
260   @link_agentnums = $curuser->agentnums;
261   $null_link = $curuser->access_right(    $opt{'agent_null_right_link'}
262                                        || $opt{'agent_null_right'}      );
263
264   my $agentnums_sql = $curuser->agentnums_sql(
265                         'null'       => $opt{'agent_null'},
266                         'null_right' => $opt{'agent_null_right'},
267                         'table'      => $opt{'query'}{'table'},
268                       );
269
270   $opt{'query'}{'extra_sql'} .=
271     ( $opt{'query'}{'extra_sql'} =~ /WHERE/i || keys %{$opt{'query'}{'hashref'}}
272       ? ' AND '
273       : ' WHERE ' ). $agentnums_sql;
274
275   $opt{'count_query'} .=
276     ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).  $agentnums_sql;
277
278   if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
279        and scalar($curuser->agentnums) > 1           ) {
280     #false laziness w/statuspos above
281     my $pos = $opt{'agent_pos'};
282
283     foreach my $att (qw( align color size style cell_style xls_format )) {
284       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
285     }
286
287     splice @{ $opt{'header'} }, $pos, 0, 'Agent'; 
288     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
289     splice @{ $opt{'style'}  }, $pos, 0, ''; 
290     splice @{ $opt{'size'}   }, $pos, 0, ''; 
291     splice @{ $opt{'fields'} }, $pos, 0,
292       sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
293     splice @{ $opt{'color'}  }, $pos, 0, '';
294     splice @{ $opt{'links'}  }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
295       if $opt{'links'};
296     splice @{ $opt{'link_onclicks'}  }, $pos, 0, ''
297       if $opt{'link_onclicks'};
298
299   }
300
301 }
302
303 if ( $opt{'disableable'} ) {
304
305   unless ( $cgi->param('showdisabled') ) { #modify searches
306
307     $opt{'query'}{'hashref'}{'disabled'} = '';
308     $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
309
310     $opt{'count_query'} .=
311       ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
312       "( disabled = '' OR disabled IS NULL )";
313
314   } elsif (    $opt{'disabled_statuspos'}
315             || $opt{'disabled_statuspos'} eq '0' ) { #add status column
316
317     my $pos = $opt{'disabled_statuspos'};
318
319     foreach my $att (qw( align style color size )) {
320       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
321     }
322
323     splice @{ $opt{'header'} }, $pos, 0, 'Status'; 
324     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
325     splice @{ $opt{'style'}  }, $pos, 0, 'b'; 
326     splice @{ $opt{'size'}   }, $pos, 0, ''; 
327     splice @{ $opt{'fields'} }, $pos, 0,
328       sub { shift->disabled ? 'DISABLED' : 'Active'; };
329     splice @{ $opt{'color'}  }, $pos, 0,
330       sub { shift->disabled ? 'FF0000'   : '00CC00'; };
331     splice @{ $opt{'links'}  }, $pos, 0, ''
332       if $opt{'links'};
333     splice @{ $opt{'link_onlicks'}  }, $pos, 0, ''
334       if $opt{'link_onlicks'};
335   }
336
337   #add show/hide disabled links
338   my $items = $opt{'name'} || PL($opt{'name_singular'});
339   if ( $cgi->param('showdisabled') ) {
340     $cgi->param('showdisabled', 0);
341     $opt{'html_posttotal'} .=
342       '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!; #"
343     $cgi->param('showdisabled', 1);
344   } else {
345     $cgi->param('showdisabled', 1);
346     $opt{'html_posttotal'} .=
347       '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!; #"
348     $cgi->param('showdisabled', 0);
349   }
350
351 }
352
353 my $limit = '';
354 my($confmax, $maxrecords, $offset );
355
356 unless ( $type =~ /^(csv|xml|\w*.xls)$/) {
357 # html mode
358   unless (exists($opt{count_query}) && length($opt{count_query})) {
359     ( $opt{count_query} = $opt{query} ) =~
360       s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
361   }
362
363   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
364     $opt{count_query} .=
365       ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
366       "( disabled = '' OR disabled IS NULL )";
367   }
368
369   unless ( $type eq 'html-print' ) {
370
371     #setup some pagination things if we're in html mode
372
373     my $conf = new FS::Conf;
374     $confmax = $conf->config('maxsearchrecordsperpage');
375     if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
376       $maxrecords = $1;
377     } else {
378       $maxrecords ||= $confmax;
379     }
380
381     $opt{'disable_maxselect'} ||= $conf->exists('disable_maxselect');
382
383     $limit = $maxrecords ? "LIMIT $maxrecords" : '';
384
385     $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
386     $limit .= " OFFSET $offset" if $offset;
387
388   }
389
390 }
391
392 #order by override
393 my $order_by = '';
394 #if ( $cgi->param('order_by') =~ /^([\w\, ]+)$/ ) {
395 #  $order_by = $1;
396 #}
397 $order_by = $cgi->param('order_by') if $cgi->param('order_by');
398
399 # run the query
400
401 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
402 my $rows;
403 if ( ref($opt{query}) ) {
404
405   my @query;
406   if (ref($opt{query}) eq 'HASH') {
407     @query = ( $opt{query} );
408
409     if ( $order_by ) {
410       if ( $opt{query}->{'order_by'} ) {
411         if ( $opt{query}->{'order_by'} =~ /^(\s*ORDER\s+BY\s+)?(\S.*)$/is ) {
412           $opt{query}->{'order_by'} = "ORDER BY $order_by, $2";
413         } else {
414           warn "unparsable query order_by: ". $opt{query}->{'order_by'};
415           die "unparsable query order_by: ". $opt{query}->{'order_by'};
416         }
417       } else {
418         $opt{query}->{'order_by'} = "ORDER BY $order_by";
419       }
420     }
421
422   } elsif (ref($opt{query}) eq 'ARRAY') {
423     @query = @{ $opt{query} };
424   } else {
425     die "invalid query reference";
426   }
427
428   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
429     #%search = ( 'disabled' => '' );
430     $opt{'query'}->{'hashref'}->{'disabled'} = '';
431     $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
432   }
433
434   #eval "use FS::$opt{'query'};";
435   my @param = qw( select table addl_from hashref extra_sql order_by );
436   $rows = [ qsearch( [ map { my $query = $_;
437                              ({ map { $_ => $query->{$_} } @param });
438                            }
439                        @query
440                      ],
441                      'order_by' => $opt{order_by}. " ". $limit,
442                    )
443           ]; 
444 } else {
445   my $sth = dbh->prepare("$opt{'query'} $limit")
446     or die "Error preparing $opt{'query'}: ". dbh->errstr;
447   $sth->execute
448     or die "Error executing $opt{'query'}: ". $sth->errstr;
449
450   #can get # of rows without fetching them all?
451   $rows = $sth->fetchall_arrayref;
452
453   $header ||= $sth->{NAME};
454 }
455
456 </%init>