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