RT# 73422 Improve customer contact report
[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) (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)cust_pkg_susp.html
135     'agent_column'          => 'COALESCE( cust_main.agentnum, prospect_main.agentnum )',
136                                 # Arbitrarily override the column used for agentvirt
137
138     # sort, link & display properties for fields
139
140     'sort_fields' => [], #optional list of field names or SQL expressions for sorts
141
142     'order_by_sql' => {              #to keep complex SQL expressions out of cgi order_by value,
143       'fieldname' => 'sql snippet',  #  maps fields/sort_fields values to sql snippets
144     }
145
146     #listref - each item is the empty string,
147     #          or a listref of link and method name to append,
148     #          or a listref of link and coderef to run and append
149     #          or a coderef that returns such a listref
150     'links'       => [],
151
152     #listref - each item is the empty string,
153     #          or a string onClick handler for the corresponding link
154     #          or a coderef that returns string onClick handler
155     'link_onclicks' => [],
156
157     #one letter for each column, left/right/center/none
158     # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
159     'align'       => 'lrc.',
160
161     #listrefs of ( scalars or coderefs )
162     # currently only HTML, maybe eventually Excel too
163     'color'       => [],
164     'size'        => [],
165     'style'       => [], #<B> or <I>, etc.
166     'cell_style'  => [], #STYLE= attribute of TR, very HTML-specific...
167
168     # Excel-specific listref of ( hashrefs or coderefs )
169     # each hashref: http://search.cpan.org/dist/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm#Format_methods_and_Format_properties
170     'xls_format' => => [],
171
172
173     # miscellany
174    'download_label' => 'Download this report',
175                         # defaults to 'Download full results'
176    'link_field'     => 'pkgpart'
177                         # will create internal links for each row,
178                         # with the value of this field as the NAME attribute
179                         # If this is a coderef, will evaluate it, passing the
180                         # row as an argument, and use the result as the NAME.
181   &>
182
183 </%doc>
184 % # if changing this, also update saved search behavior to match!
185 % if ( $type eq 'csv' ) {
186 %
187 <% include('search-csv.html',  header=>$header, rows=>$rows, opt=>\%opt ) %>
188 %
189 % } elsif ( $type =~ /\.xls$/ ) {
190 %
191 <& 'search-xls.html',  header=>$header, rows=>$rows, opt=>\%opt &>\
192 % # prevent the caller from polluting our output stream
193 % $m->abort;
194 %
195 % } elsif ( $type eq 'xml' ) {
196 %
197 <% include('search-xml.html',  rows=>$rows, opt=>\%opt ) %>
198 %
199 % } else {
200 %
201 <% include('search-html.html',
202              type           => $type,
203              header         => $header,
204              rows           => $rows,
205              link_agentnums => \@link_agentnums,
206              null_link      => $null_link,
207              confmax        => $confmax,
208              maxrecords     => $maxrecords,
209              offset         => $offset,
210              totals         => $totals,
211              opt            => \%opt
212           )
213 %>
214 %
215 % }
216 <%init>
217
218 my(%opt) = @_;
219 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
220
221 my $curuser = $FS::CurrentUser::CurrentUser;
222
223 $m->comp('/elements/handle_uri_query');
224
225 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|xml|select|html(-print)?)$/
226            ? $1 : 'html' ;
227
228 if ( !$curuser->access_right('Download report data') ) {
229   $opt{'disable_download'} = 1;
230   $type = 'html';
231 }
232
233 # split/map aligns here before doing anything else
234 my %align = (
235   'l' => 'left',
236   'r' => 'right',
237   'c' => 'center',
238   ' ' => '',
239   '.' => '',
240 );
241
242 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
243   unless !$opt{align} || ref($opt{align});
244
245 if($type =~ /csv|xls/) {
246   my $h = $opt{'header'};
247   my @del;
248   my $i = 0;
249   do {
250     if( ref($h->[$i]) and exists($h->[$i]->{'nodownload'}) ) {
251       splice(@{$opt{$_}}, $i, 1) foreach
252         qw(header footer fields links link_onclicks
253            align color size style cell_style xls_format);
254     }
255     else {
256       $i++;
257     }
258   } while ( exists($h->[$i]) );
259 }
260
261 # wtf?
262 $opt{disable_download} = 0
263   if $opt{disable_download} && $curuser->access_right('Configuration download');
264
265 $opt{disable_download} = 1
266   if $opt{really_disable_download};
267
268 # get our queries ready
269 my $query = $opt{query} or die "query required";
270 my $count_query = $opt{count_query} or die "count_query required";
271 # there was a default count_query but it hasn't worked in about ten years
272
273 # set up agent restriction
274 my @link_agentnums = ();
275 my $null_link = '';
276 if ( $opt{'agent_virt'} ) {
277
278   @link_agentnums = $curuser->agentnums;
279   $null_link = $curuser->access_right(    $opt{'agent_null_right_link'}
280                                        || $opt{'agent_null_right'}      );
281
282   my $agentnums_sql = $curuser->agentnums_sql(
283                         'null'       => $opt{'agent_null'},
284                         'null_right' => $opt{'agent_null_right'},
285                         'table'      => $query->{'table'},
286                         'column'     => $opt{'agent_column'},
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_onlicks'}  }, $pos, 0, ''
361       if $opt{'link_onlicks'};
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     $opt{'disable_maxselect'} ||= $conf->exists('disable_maxselect');
392     unless ($opt{'disable_maxselect'}) {
393       $confmax = $conf->config('maxsearchrecordsperpage') || 100;
394       if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
395         $maxrecords = $1;
396       } else {
397         $maxrecords ||= $confmax;
398       }
399     }
400
401     $limit = $maxrecords ? "LIMIT $maxrecords" : '';
402
403     $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
404     $limit .= " OFFSET $offset" if $offset;
405
406   }
407
408 }
409
410 #order by override
411 my $order_by = $opt{order_by} || '';
412 $order_by = $cgi->param('order_by') if $cgi->param('order_by');
413
414 # run the query
415
416 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
417 my $rows;
418
419 my ($order_by_key,$order_by_desc) = ($order_by =~ /^\s*(.*?)(\s+DESC)?\s*$/i);
420 my $union_order_by;
421 $opt{'order_by_sql'} ||= {};
422 $order_by_desc ||= '';
423 $order_by = $opt{'order_by_sql'}{$order_by_key} . $order_by_desc
424   if $opt{'order_by_sql'}{$order_by_key};
425
426 if ( ref $query ) {
427   my @query;
428   if (ref($query) eq 'HASH') {
429     @query = $query;
430
431     # Assemble peices of order_by information as SQL fragment,
432     # store as query->{order_by}
433     if ( $order_by ) {
434       if ( $query->{'order_by'} ) {
435         if ( $query->{'order_by'} =~ /^(\s*ORDER\s+BY\s+)?(\S.*)$/is ) {
436           $query->{'order_by'} = "ORDER BY $order_by, $2";
437         } else {
438           warn "unparsable query order_by: ". $query->{'order_by'};
439           die "unparsable query order_by: ". $query->{'order_by'};
440         }
441       } else {
442         $query->{'order_by'} = "ORDER BY $order_by";
443       }
444     }
445     $query->{'order_by'} .= " $limit";
446
447   } elsif (ref($query) eq 'ARRAY') {
448     # Presented query is a UNION query, with multiple query references
449     @query = @{ $query };
450
451     # Assemble peices of order_by information as SQL fragment,
452     # store as $union_order_by.  Omit order_by/limit from individual
453     # $query hashrefs, because this is a union query
454     #
455     # ! Currently, order_by data is only fetched from $cgi->param('order_by')
456     # ! for union queries. If it eventually needs to be passed within query
457     # ! hashrefs, or as mason template options, would need implemented
458     $union_order_by = " ORDER BY $order_by " if $order_by;
459     $union_order_by .= " $limit " if $limit;
460
461   } else {
462     die "invalid query reference ($query)";
463   }
464
465   #eval "use FS::$opt{'query'};";
466   my @param = qw( select table addl_from hashref extra_sql order_by debug );
467
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>