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