git merge bs
[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 (corner cases only) 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 <<<<<<< HEAD
37    
38     #required (now even if 'query' is an SQL query string)
39 =======
40
41     #required unless 'query' is an SQL query string (shouldn't be...)
42 >>>>>>> 95144265eeb3ecd13b16708dbdd75dd3701f92ad
43     'count_query' => 'SELECT COUNT(*) FROM tablename',
44
45     ###
46     # recommended / common
47     ###
48
49     #listref of column labels, <TH>
50     #recommended unless 'query' is an SQL query string
51     # (if not specified the database column names will be used) (XXX this is not currently working either)
52     'header'      => [ '#',
53                        'Item',
54                        { 'label' => 'Another Item',
55
56                        },
57                      ],
58
59     #listref - each item is a literal column name (or method) or coderef
60     #if not specified all columns will be shown (XXX this is not currently working?)
61     'fields'      => [
62                        'column',
63                        sub { my $row = shift; $row->column; },
64                      ],
65
66     #redirect if there's only one item...
67     # listref of URL base and column name (or method)
68     # or a coderef that returns the same
69     'redirect' => sub { my( $record, $cgi ) = @_;
70                         [ popurl(2).'view/item.html', 'primary_key' ];
71                       },
72
73     #redirect if there's no items
74     # scalar URL or a coderef that returns a URL
75     'redirect_empty' => sub { my( $cgi ) = @_;
76                               popurl(2).'view/item.html';
77                             },
78
79     ###
80     # optional
81     ###
82
83     # some HTML callbacks...
84     'menubar'          => '', #menubar arrayref
85     'html_init'        => '', #after the header/menubar and before the pager
86     'html_form'        => '', #after the pager, right before the results
87                               # (only shown if there are results)
88                               # (use this for any form-opening tag rather than
89                               #  html_init, to avoid a nested form)
90     'html_foot'        => '', #at the bottom
91     'html_posttotal'   => '', #at the bottom
92                               # (these three can be strings or coderefs)
93
94     'count_addl' => [], #additional count fields listref of sprintf strings or coderefs
95                         # [ $money_char.'%.2f total paid', ],
96
97     #second (smaller) header line, currently only for HTML
98     'header2      => [ '#',
99                        'Item',
100                        { 'label' => 'Another Item',
101
102                        },
103                      ],
104
105     #listref of column footers
106     'footer'      => [],
107
108     #disabling things
109     'disable_download'  => '', # set true to hide the CSV/Excel download links
110     'disable_total'     => '', # set true to hide the total"
111     'disable_maxselect' => '', # set true to disable record/page selection
112     'disable_nonefound' => '', # set true to disable the "No matching Xs found"
113                                # message
114     'nohtmlheader'      => '', # set true to remove the header and menu bar
115
116     #handling "disabled" fields in the records
117     'disableable' => 1,  # set set to 1 (or column position for "disabled"
118                          # status col) to enable if this table has a "disabled"
119                          # field, to hide disabled records & have
120                          # "show disabled/hide disabled" links
121                          #(can't be used with a literal query)
122     'disabled_statuspos' => 3, #optional position (starting from 0) to insert
123                                #a Status column when showing disabled records
124                                #(query needs to be a qsearch hashref and
125                                # header & fields need to be defined)
126
127     #handling agent virtualization
128     'agent_virt'            => 1, # set true if this search should be
129                                   # agent-virtualized
130     'agent_null'            => 1, # set true to view global records always
131     'agent_null_right'      => 'Access Right', # optional right to view global
132                                                # records
133     'agent_null_right_link' => 'Access Right'  # optional right to link to
134                                                # global records; defaults to
135                                                # same as agent_null_right
136     'agent_pos'             => 3, # optional position (starting from 0) to
137                                   # insert an Agent column (query needs to be a
138                                   # qsearch hashref and header & fields need to
139                                   # be defined)
140
141     # sort, link & display properties for fields
142
143     'sort_fields' => [], #optional list of field names or SQL expressions for sorts
144
145     'order_by_sql' => {              #to keep complex SQL expressions out of cgi order_by value,
146       'fieldname' => 'sql snippet',  #  maps fields/sort_fields values to sql snippets
147     }
148
149     #listref - each item is the empty string,
150     #          or a listref of link and method name to append,
151     #          or a listref of link and coderef to run and append
152     #          or a coderef that returns such a listref
153     'links'       => [],
154
155     #listref - each item is the empty string,
156     #          or a string onClick handler for the corresponding link
157     #          or a coderef that returns string onClick handler
158     'link_onclicks' => [],
159
160     #one letter for each column, left/right/center/none
161     # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
162     'align'       => 'lrc.',
163
164     #listrefs of ( scalars or coderefs )
165     # currently only HTML, maybe eventually Excel too
166     'color'       => [],
167     'size'        => [],
168     'style'       => [], #<B> or <I>, etc.
169     'cell_style'  => [], #STYLE= attribute of TR, very HTML-specific...
170
171     # Excel-specific listref of ( hashrefs or coderefs )
172     # each hashref: http://search.cpan.org/dist/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm#Format_methods_and_Format_properties
173     'xls_format' => => [],
174
175
176     # miscellany
177    'download_label' => 'Download this report',
178                         # defaults to 'Download full results'
179    'link_field'     => 'pkgpart'
180                         # will create internal links for each row,
181                         # with the value of this field as the NAME attribute
182                         # If this is a coderef, will evaluate it, passing the
183                         # row as an argument, and use the result as the NAME.
184   &>
185
186 </%doc>
187 % # if changing this, also update saved search behavior to match!
188 % if ( $type eq 'csv' ) {
189 %
190 <% include('search-csv.html',  header=>$header, rows=>$rows, opt=>\%opt ) %>
191 %
192 % } elsif ( $type =~ /\.xls$/ ) {
193 %
194 <& 'search-xls.html',  header=>$header, rows=>$rows, opt=>\%opt &>\
195 % # prevent the caller from polluting our output stream
196 % $m->abort;
197 %
198 % } elsif ( $type eq 'xml' ) {
199 %
200 <% include('search-xml.html',  rows=>$rows, opt=>\%opt ) %>
201 %
202 % } else {
203 %
204 <% include('search-html.html',
205              type           => $type,
206              header         => $header,
207              rows           => $rows,
208              link_agentnums => \@link_agentnums,
209              null_link      => $null_link,
210              confmax        => $confmax,
211              maxrecords     => $maxrecords,
212              offset         => $offset,
213              totals         => $totals,
214              opt            => \%opt
215           )
216 %>
217 %
218 % }
219 <%init>
220
221 my(%opt) = @_;
222 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
223
224 my $curuser = $FS::CurrentUser::CurrentUser;
225
226 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|xml|select|html(-print)?)$/
227            ? $1 : 'html' ;
228
229 if ( !$curuser->access_right('Download report data') ) {
230   $opt{'disable_download'} = 1;
231   $type = 'html';
232 }
233
234 # split/map aligns here before doing anything else
235 my %align = (
236   'l' => 'left',
237   'r' => 'right',
238   'c' => 'center',
239   ' ' => '',
240   '.' => '',
241 );
242
243 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
244   unless !$opt{align} || ref($opt{align});
245
246 if($type =~ /csv|xls/) {
247   my $h = $opt{'header'};
248   my @del;
249   my $i = 0;
250   do {
251     if( ref($h->[$i]) and exists($h->[$i]->{'nodownload'}) ) {
252       splice(@{$opt{$_}}, $i, 1) foreach
253         qw(header footer fields links link_onclicks
254            align color size style cell_style xls_format);
255     }
256     else {
257       $i++;
258     }
259   } while ( exists($h->[$i]) );
260 }
261
262 # wtf?
263 $opt{disable_download} = 0
264   if $opt{disable_download} && $curuser->access_right('Configuration download');
265
266 $opt{disable_download} = 1
267   if $opt{really_disable_download};
268
269 # get our queries ready
270 my $query = $opt{query} or die "query required";
271 my $count_query = $opt{count_query} or die "count_query required";
272 # there was a default count_query but it hasn't worked in about ten years
273
274 # set up agent restriction
275 my @link_agentnums = ();
276 my $null_link = '';
277 if ( $opt{'agent_virt'} ) {
278
279   @link_agentnums = $curuser->agentnums;
280   $null_link = $curuser->access_right(    $opt{'agent_null_right_link'}
281                                        || $opt{'agent_null_right'}      );
282
283   my $agentnums_sql = $curuser->agentnums_sql(
284                         'null'       => $opt{'agent_null'},
285                         'null_right' => $opt{'agent_null_right'},
286                         'table'      => $query->{'table'},
287                       );
288
289   # this is ridiculous, but we do have searches where $query has constraints
290   # and $count_query doesn't, or vice versa.
291   if ( $query->{'extra_sql'} =~ /\bWHERE\b/i or keys %{$query->{hashref}} ) {
292     $query->{'extra_sql'} .= " AND $agentnums_sql";
293   } else {
294     $query->{'extra_sql'} .= " WHERE $agentnums_sql";
295   }
296
297   if ( $count_query =~ /\bWHERE\b/i ) {
298     $count_query .= " AND $agentnums_sql";
299   } else {
300     $count_query .= " WHERE $agentnums_sql";
301   }
302
303   if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
304        and scalar($curuser->agentnums) > 1           ) {
305     #false laziness w/statuspos above
306     my $pos = $opt{'agent_pos'};
307
308     foreach my $att (qw( align color size style cell_style xls_format )) {
309       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
310     }
311
312     splice @{ $opt{'header'} }, $pos, 0, 'Agent';
313     splice @{ $opt{'align'}  }, $pos, 0, 'c';
314     splice @{ $opt{'style'}  }, $pos, 0, '';
315     splice @{ $opt{'size'}   }, $pos, 0, '';
316     splice @{ $opt{'fields'} }, $pos, 0,
317       sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
318     splice @{ $opt{'color'}  }, $pos, 0, '';
319     splice @{ $opt{'links'}  }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
320       if $opt{'links'};
321     splice @{ $opt{'link_onclicks'}  }, $pos, 0, ''
322       if $opt{'link_onclicks'};
323
324   }
325
326 }
327
328 if ( $opt{'disableable'} ) {
329
330   unless ( $cgi->param('showdisabled') ) { #modify searches
331
332     $query->{'hashref'}{'disabled'} = '';
333     $query->{'extra_sql'} =~ s/^\s*\bWHERE\b/ AND/i;
334
335     my $table = $query->{'table'};
336
337     $count_query .=
338       ( $count_query =~ /\bWHERE\b/i ? ' AND ' : ' WHERE ' ).
339       "( $table.disabled = '' OR $table.disabled IS NULL )";
340
341   } elsif (    $opt{'disabled_statuspos'}
342             || $opt{'disabled_statuspos'} eq '0' ) { #add status column
343
344     my $pos = $opt{'disabled_statuspos'};
345
346     foreach my $att (qw( align style color size )) {
347       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
348     }
349
350     splice @{ $opt{'header'} }, $pos, 0, 'Status';
351     splice @{ $opt{'align'}  }, $pos, 0, 'c';
352     splice @{ $opt{'style'}  }, $pos, 0, 'b';
353     splice @{ $opt{'size'}   }, $pos, 0, '';
354     splice @{ $opt{'fields'} }, $pos, 0,
355       sub { shift->disabled ? 'DISABLED' : 'Active'; };
356     splice @{ $opt{'color'}  }, $pos, 0,
357       sub { shift->disabled ? 'FF0000'   : '00CC00'; };
358     splice @{ $opt{'links'}  }, $pos, 0, ''
359       if $opt{'links'};
360     splice @{ $opt{'link_onclicks'}  }, $pos, 0, ''
361       if $opt{'link_onclicks'};
362   }
363
364   #add show/hide disabled links
365   my $items = $opt{'name'} || PL($opt{'name_singular'});
366   if ( $cgi->param('showdisabled') ) {
367     $cgi->param('showdisabled', 0);
368     $opt{'html_posttotal'} .=
369       '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!; #"
370     $cgi->param('showdisabled', 1);
371   } else {
372     $cgi->param('showdisabled', 1);
373     $opt{'html_posttotal'} .=
374       '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!; #"
375     $cgi->param('showdisabled', 0);
376   }
377
378 }
379
380 my $limit = '';
381 my($confmax, $maxrecords, $offset );
382
383 unless ( $type =~ /^(csv|xml|\w*.xls)$/) {
384 # html mode
385
386   unless ( $type eq 'html-print' ) {
387
388     #setup some pagination things if we're in html mode
389
390     my $conf = new FS::Conf;
391     $confmax = $conf->config('maxsearchrecordsperpage') || 100;
392     if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
393       $maxrecords = $1;
394     } else {
395       $maxrecords ||= $confmax;
396     }
397
398     $opt{'disable_maxselect'} ||= $conf->exists('disable_maxselect');
399
400     $limit = $maxrecords ? "LIMIT $maxrecords" : '';
401
402     $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
403     $limit .= " OFFSET $offset" if $offset;
404
405   }
406
407 }
408
409 #order by override
410 my $order_by = $opt{order_by} || '';
411 $order_by = $cgi->param('order_by') if $cgi->param('order_by');
412
413 # run the query
414
415 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
416 my $rows;
417
418 my ($order_by_key,$order_by_desc) = ($order_by =~ /^\s*(.*?)(\s+DESC)?\s*$/i);
419 my $union_order_by;
420 $opt{'order_by_sql'} ||= {};
421 $order_by_desc ||= '';
422 $order_by = $opt{'order_by_sql'}{$order_by_key} . $order_by_desc
423   if $opt{'order_by_sql'}{$order_by_key};
424
425 if ( ref $query ) {
426   my @query;
427   if (ref($query) eq 'HASH') {
428     @query = $query;
429
430     # Assemble peices of order_by information as SQL fragment,
431     # store as query->{order_by}
432     if ( $order_by ) {
433       if ( $query->{'order_by'} ) {
434         if ( $query->{'order_by'} =~ /^(\s*ORDER\s+BY\s+)?(\S.*)$/is ) {
435           $query->{'order_by'} = "ORDER BY $order_by, $2";
436         } else {
437           warn "unparsable query order_by: ". $query->{'order_by'};
438           die "unparsable query order_by: ". $query->{'order_by'};
439         }
440       } else {
441         $query->{'order_by'} = "ORDER BY $order_by";
442       }
443     }
444     $query->{'order_by'} .= " $limit";
445
446   } elsif (ref($query) eq 'ARRAY') {
447     # Presented query is a UNION query, with multiple query references
448     @query = @{ $query };
449
450     # Assemble peices of order_by information as SQL fragment,
451     # store as $union_order_by.  Omit order_by/limit from individual
452     # $query hashrefs, because this is a union query
453     #
454     # ! Currently, order_by data is only fetched from $cgi->param('order_by')
455     # ! for union queries. If it eventually needs to be passed within query
456     # ! hashrefs, or as mason template options, would need implemented
457     $union_order_by = " ORDER BY $order_by " if $order_by;
458     $union_order_by .= " $limit " if $limit;
459
460   } else {
461     die "invalid query reference ($query)";
462   }
463
464   #eval "use FS::$opt{'query'};";
465   my @param = qw( select table addl_from hashref extra_sql order_by debug );
466   if ($opt{classname_from_column}) {
467     # Perform a union of multiple queries, while using the
468     # classname_from_column qsearch union option
469
470     # Constrain hashkeys for each query from @param
471     @query = map{
472       my $query = $_;
473       my $new_query = {};
474       $new_query->{$_} = $query->{$_} for @param;
475       $new_query;
476     } @query;
477
478     $rows = [
479       qsearch(
480         \@query,
481         order_by => $union_order_by,
482         classname_from_column => 1,
483       )
484     ];
485
486   } else {
487     # default perform a query with qsearch
488     $rows = [ qsearch( [ map { my $query = $_;
489                                ({ map { $_ => $query->{$_} } @param });
490                              }
491                          @query
492                        ],
493                        #'order_by' => $opt{order_by}. " ". $limit,
494                      )
495             ];
496   }
497 } else { # not ref $query; plain SQL (still used as of 07/2015)
498
499   $query .= " $limit";
500   my $sth = dbh->prepare($query)
501     or die "Error preparing $query: ". dbh->errstr;
502   $sth->execute
503     or die "Error executing $query: ". $sth->errstr;
504
505   $rows = $sth->fetchall_arrayref;
506   $header ||= $sth->{NAME};
507 }
508
509 # run the count query to get number of rows and other totals
510 my $count_sth = dbh->prepare($count_query);
511 $count_sth->execute
512   or die "Error executing '$count_query': ".$count_sth->errstr;
513 my $totals = $count_sth->fetchrow_arrayref;
514
515 push @$rows, $opt{'footer_data'} if $opt{'footer_data'};
516
517 </%init>