5 <& elements/search.html,
11 'title' => 'Page title',
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
19 #literal SQL query string (corner cases only) or qsearch hashref or arrayref
20 #of qsearch hashrefs for a union of qsearches
22 'table' => 'tablename',
23 #everything else is optional...
24 'hashref' => { 'field' => 'value',
25 'field' => { 'op' => '<',
30 'addl_from' => '', #'LEFT JOIN othertable USING ( key )',
31 'extra_sql' => '', #'AND otherstuff', #'WHERE onlystuff',
32 'order_by' => 'ORDER BY something',
35 # "select * from tablename";
38 #required (now even if 'query' is an SQL query string)
41 #required unless 'query' is an SQL query string (shouldn't be...)
42 >>>>>>> 95144265eeb3ecd13b16708dbdd75dd3701f92ad
43 'count_query' => 'SELECT COUNT(*) FROM tablename',
46 # recommended / common
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)
54 { 'label' => 'Another Item',
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?)
63 sub { my $row = shift; $row->column; },
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' ];
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';
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)
94 'count_addl' => [], #additional count fields listref of sprintf strings or coderefs
95 # [ $money_char.'%.2f total paid', ],
97 #second (smaller) header line, currently only for HTML
100 { 'label' => 'Another Item',
105 #listref of column footers
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"
114 'nohtmlheader' => '', # set true to remove the header and menu bar
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)
127 #handling agent virtualization
128 'agent_virt' => 1, # set true if this search should be
130 'agent_null' => 1, # set true to view global records always
131 'agent_null_right' => 'Access Right', # optional right to view global
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
141 # sort, link & display properties for fields
143 'sort_fields' => [], #optional list of field names or SQL expressions for sorts
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
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
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' => [],
160 #one letter for each column, left/right/center/none
161 # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
164 #listrefs of ( scalars or coderefs )
165 # currently only HTML, maybe eventually Excel too
168 'style' => [], #<B> or <I>, etc.
169 'cell_style' => [], #STYLE= attribute of TR, very HTML-specific...
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' => => [],
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.
187 % # if changing this, also update saved search behavior to match!
188 % if ( $type eq 'csv' ) {
190 <% include('search-csv.html', header=>$header, rows=>$rows, opt=>\%opt ) %>
192 % } elsif ( $type =~ /\.xls$/ ) {
194 <& 'search-xls.html', header=>$header, rows=>$rows, opt=>\%opt &>\
195 % # prevent the caller from polluting our output stream
198 % } elsif ( $type eq 'xml' ) {
200 <% include('search-xml.html', rows=>$rows, opt=>\%opt ) %>
204 <% include('search-html.html',
208 link_agentnums => \@link_agentnums,
209 null_link => $null_link,
211 maxrecords => $maxrecords,
222 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
224 my $curuser = $FS::CurrentUser::CurrentUser;
226 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|xml|select|html(-print)?)$/
229 if ( !$curuser->access_right('Download report data') ) {
230 $opt{'disable_download'} = 1;
234 # split/map aligns here before doing anything else
243 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
244 unless !$opt{align} || ref($opt{align});
246 if($type =~ /csv|xls/) {
247 my $h = $opt{'header'};
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);
259 } while ( exists($h->[$i]) );
263 $opt{disable_download} = 0
264 if $opt{disable_download} && $curuser->access_right('Configuration download');
266 $opt{disable_download} = 1
267 if $opt{really_disable_download};
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
274 # set up agent restriction
275 my @link_agentnums = ();
277 if ( $opt{'agent_virt'} ) {
279 @link_agentnums = $curuser->agentnums;
280 $null_link = $curuser->access_right( $opt{'agent_null_right_link'}
281 || $opt{'agent_null_right'} );
283 my $agentnums_sql = $curuser->agentnums_sql(
284 'null' => $opt{'agent_null'},
285 'null_right' => $opt{'agent_null_right'},
286 'table' => $query->{'table'},
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";
294 $query->{'extra_sql'} .= " WHERE $agentnums_sql";
297 if ( $count_query =~ /\bWHERE\b/i ) {
298 $count_query .= " AND $agentnums_sql";
300 $count_query .= " WHERE $agentnums_sql";
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'};
308 foreach my $att (qw( align color size style cell_style xls_format )) {
309 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
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' ]
321 splice @{ $opt{'link_onclicks'} }, $pos, 0, ''
322 if $opt{'link_onclicks'};
328 if ( $opt{'disableable'} ) {
330 unless ( $cgi->param('showdisabled') ) { #modify searches
332 $query->{'hashref'}{'disabled'} = '';
333 $query->{'extra_sql'} =~ s/^\s*\bWHERE\b/ AND/i;
335 my $table = $query->{'table'};
338 ( $count_query =~ /\bWHERE\b/i ? ' AND ' : ' WHERE ' ).
339 "( $table.disabled = '' OR $table.disabled IS NULL )";
341 } elsif ( $opt{'disabled_statuspos'}
342 || $opt{'disabled_statuspos'} eq '0' ) { #add status column
344 my $pos = $opt{'disabled_statuspos'};
346 foreach my $att (qw( align style color size )) {
347 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
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, ''
360 splice @{ $opt{'link_onclicks'} }, $pos, 0, ''
361 if $opt{'link_onclicks'};
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);
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);
381 my($confmax, $maxrecords, $offset );
383 unless ( $type =~ /^(csv|xml|\w*.xls)$/) {
386 unless ( $type eq 'html-print' ) {
388 #setup some pagination things if we're in html mode
390 my $conf = new FS::Conf;
391 $confmax = $conf->config('maxsearchrecordsperpage') || 100;
392 if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
395 $maxrecords ||= $confmax;
398 $opt{'disable_maxselect'} ||= $conf->exists('disable_maxselect');
400 $limit = $maxrecords ? "LIMIT $maxrecords" : '';
402 $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
403 $limit .= " OFFSET $offset" if $offset;
410 my $order_by = $opt{order_by} || '';
411 $order_by = $cgi->param('order_by') if $cgi->param('order_by');
415 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
418 my ($order_by_key,$order_by_desc) = ($order_by =~ /^\s*(.*?)(\s+DESC)?\s*$/i);
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};
427 if (ref($query) eq 'HASH') {
430 # Assemble peices of order_by information as SQL fragment,
431 # store as query->{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";
437 warn "unparsable query order_by: ". $query->{'order_by'};
438 die "unparsable query order_by: ". $query->{'order_by'};
441 $query->{'order_by'} = "ORDER BY $order_by";
444 $query->{'order_by'} .= " $limit";
446 } elsif (ref($query) eq 'ARRAY') {
447 # Presented query is a UNION query, with multiple query references
448 @query = @{ $query };
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
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;
461 die "invalid query reference ($query)";
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
470 # Constrain hashkeys for each query from @param
474 $new_query->{$_} = $query->{$_} for @param;
481 order_by => $union_order_by,
482 classname_from_column => 1,
487 # default perform a query with qsearch
488 $rows = [ qsearch( [ map { my $query = $_;
489 ({ map { $_ => $query->{$_} } @param });
493 #'order_by' => $opt{order_by}. " ". $limit,
497 } else { # not ref $query; plain SQL (still used as of 07/2015)
500 my $sth = dbh->prepare($query)
501 or die "Error preparing $query: ". dbh->errstr;
503 or die "Error executing $query: ". $sth->errstr;
505 $rows = $sth->fetchall_arrayref;
506 $header ||= $sth->{NAME};
509 # run the count query to get number of rows and other totals
510 my $count_sth = dbh->prepare($count_query);
512 or die "Error executing '$count_query': ".$count_sth->errstr;
513 my $totals = $count_sth->fetchrow_arrayref;
515 push @$rows, $opt{'footer_data'} if $opt{'footer_data'};