fix processing of aligns with agent-virt, #25944
[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
136     # sort, link & display properties for fields
137
138     'sort_fields' => [], #optional list of field names or SQL expressions for
139                          # sorts
140    
141     #listref - each item is the empty string,
142     #          or a listref of link and method name to append,
143     #          or a listref of link and coderef to run and append
144     #          or a coderef that returns such a listref
145     'links'       => [],
146
147     #listref - each item is the empty string,
148     #          or a string onClick handler for the corresponding link
149     #          or a coderef that returns string onClick handler
150     'link_onclicks' => [],
151
152     #one letter for each column, left/right/center/none
153     # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
154     'align'       => 'lrc.',
155    
156     #listrefs of ( scalars or coderefs )
157     # currently only HTML, maybe eventually Excel too
158     'color'       => [],
159     'size'        => [],
160     'style'       => [], #<B> or <I>, etc.
161     'cell_style'  => [], #STYLE= attribute of TR, very HTML-specific...
162
163     # Excel-specific listref of ( hashrefs or coderefs )
164     # each hashref: http://search.cpan.org/dist/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm#Format_methods_and_Format_properties
165     'xls_format' => => [],
166    
167
168     # miscellany
169    'download_label' => 'Download this report',
170                         # defaults to 'Download full results' 
171    'link_field'     => 'pkgpart'
172                         # will create internal links for each row,
173                         # with the value of this field as the NAME attribute
174                         # If this is a coderef, will evaluate it, passing the
175                         # row as an argument, and use the result as the NAME.
176   &>
177
178 </%doc>
179 % if ( $type eq 'csv' ) {
180 %
181 <% include('search-csv.html',  header=>$header, rows=>$rows, opt=>\%opt ) %>
182 %
183 % } elsif ( $type =~ /\.xls$/ ) {
184 %
185 <& 'search-xls.html',  header=>$header, rows=>$rows, opt=>\%opt &>\
186 % # prevent the caller from polluting our output stream
187 % $m->abort;
188 %
189 % } elsif ( $type eq 'xml' ) {
190 %
191 <% include('search-xml.html',  rows=>$rows, opt=>\%opt ) %>
192 %
193 % } else {
194 %
195 <% include('search-html.html',
196              type           => $type,
197              header         => $header,
198              rows           => $rows,
199              link_agentnums => \@link_agentnums,
200              null_link      => $null_link,
201              confmax        => $confmax,
202              maxrecords     => $maxrecords,
203              offset         => $offset,
204              totals         => $totals,
205              opt            => \%opt
206           )
207 %>
208 %
209 % } 
210 <%init>
211
212 my(%opt) = @_;
213 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
214
215 my $curuser = $FS::CurrentUser::CurrentUser;
216
217 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|xml|select|html(-print)?)$/
218            ? $1 : 'html' ;
219
220 if ( !$curuser->access_right('Download report data') ) {
221   $opt{'disable_download'} = 1;
222   $type = 'html';
223 }
224
225 if($type =~ /csv|xls/) {
226   my $h = $opt{'header'};
227   my @del;
228   my $i = 0;
229   do {
230     if( ref($h->[$i]) and exists($h->[$i]->{'nodownload'}) ) {
231       splice(@{$opt{$_}}, $i, 1) foreach
232         qw(header footer fields links link_onclicks
233            align color size style cell_style xls_format);
234     }
235     else {
236       $i++;
237     }
238   } while ( exists($h->[$i]) );
239 }
240
241 # wtf?
242 $opt{disable_download} = 0
243   if $opt{disable_download} && $curuser->access_right('Configuration download');
244
245 $opt{disable_download} = 1
246   if $opt{really_disable_download};
247
248 # split/map aligns here, so that agent_virt can add a column
249 # (search-html.html will split aligns also if they aren't already split)
250 my %align = (
251   'l' => 'left',
252   'r' => 'right',
253   'c' => 'center',
254   ' ' => '',
255   '.' => '',
256 );
257 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
258   unless !$opt{align} || ref($opt{align});
259
260 # get our queries ready
261 my $query = $opt{query} or die "query required";
262 my $count_query = $opt{count_query} or die "count_query required";
263 # there was a default count_query but it hasn't worked in about ten years
264
265 # set up agent restriction
266 my @link_agentnums = ();
267 my $null_link = '';
268 if ( $opt{'agent_virt'} ) {
269
270   @link_agentnums = $curuser->agentnums;
271   $null_link = $curuser->access_right(    $opt{'agent_null_right_link'}
272                                        || $opt{'agent_null_right'}      );
273
274   my $agentnums_sql = $curuser->agentnums_sql(
275                         'null'       => $opt{'agent_null'},
276                         'null_right' => $opt{'agent_null_right'},
277                         'table'      => $query->{'table'},
278                       );
279
280   if ( $query->{'extra_sql'} =~ /\bWHERE\b/i or keys %{$query->{hashref}} ) {
281     $query->{'extra_sql'} .= " AND $agentnums_sql";
282     $count_query .= " AND $agentnums_sql";
283   } else {
284     $query->{'extra_sql'} .= " WHERE $agentnums_sql";
285     $count_query .= " WHERE $agentnums_sql";
286   }
287
288   if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
289        and scalar($curuser->agentnums) > 1           ) {
290     #false laziness w/statuspos above
291     my $pos = $opt{'agent_pos'};
292
293     foreach my $att (qw( align color size style cell_style xls_format )) {
294       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
295     }
296
297     splice @{ $opt{'header'} }, $pos, 0, 'Agent'; 
298     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
299     splice @{ $opt{'style'}  }, $pos, 0, ''; 
300     splice @{ $opt{'size'}   }, $pos, 0, ''; 
301     splice @{ $opt{'fields'} }, $pos, 0,
302       sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
303     splice @{ $opt{'color'}  }, $pos, 0, '';
304     splice @{ $opt{'links'}  }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
305       if $opt{'links'};
306     splice @{ $opt{'link_onclicks'}  }, $pos, 0, ''
307       if $opt{'link_onclicks'};
308
309   }
310
311 }
312
313 if ( $opt{'disableable'} ) {
314
315   unless ( $cgi->param('showdisabled') ) { #modify searches
316
317     $query->{'hashref'}{'disabled'} = '';
318     $query->{'extra_sql'} =~ s/^\s*\bWHERE\b/ AND/i;
319
320     my $table = $query->{'table'};
321
322     $count_query .= 
323       ( $count_query =~ /\bWHERE\b/i ? ' AND ' : ' WHERE ' ).
324       "( $table.disabled = '' OR $table.disabled IS NULL )";
325
326   } elsif (    $opt{'disabled_statuspos'}
327             || $opt{'disabled_statuspos'} eq '0' ) { #add status column
328
329     my $pos = $opt{'disabled_statuspos'};
330
331     foreach my $att (qw( align style color size )) {
332       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
333     }
334
335     splice @{ $opt{'header'} }, $pos, 0, 'Status'; 
336     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
337     splice @{ $opt{'style'}  }, $pos, 0, 'b'; 
338     splice @{ $opt{'size'}   }, $pos, 0, ''; 
339     splice @{ $opt{'fields'} }, $pos, 0,
340       sub { shift->disabled ? 'DISABLED' : 'Active'; };
341     splice @{ $opt{'color'}  }, $pos, 0,
342       sub { shift->disabled ? 'FF0000'   : '00CC00'; };
343     splice @{ $opt{'links'}  }, $pos, 0, ''
344       if $opt{'links'};
345     splice @{ $opt{'link_onlicks'}  }, $pos, 0, ''
346       if $opt{'link_onlicks'};
347   }
348
349   #add show/hide disabled links
350   my $items = $opt{'name'} || PL($opt{'name_singular'});
351   if ( $cgi->param('showdisabled') ) {
352     $cgi->param('showdisabled', 0);
353     $opt{'html_posttotal'} .=
354       '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!; #"
355     $cgi->param('showdisabled', 1);
356   } else {
357     $cgi->param('showdisabled', 1);
358     $opt{'html_posttotal'} .=
359       '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!; #"
360     $cgi->param('showdisabled', 0);
361   }
362
363 }
364
365 my $limit = '';
366 my($confmax, $maxrecords, $offset );
367
368 unless ( $type =~ /^(csv|xml|\w*.xls)$/) {
369 # html mode
370
371   unless ( $type eq 'html-print' ) {
372
373     #setup some pagination things if we're in html mode
374
375     my $conf = new FS::Conf;
376     $confmax = $conf->config('maxsearchrecordsperpage');
377     if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
378       $maxrecords = $1;
379     } else {
380       $maxrecords ||= $confmax;
381     }
382
383     $opt{'disable_maxselect'} ||= $conf->exists('disable_maxselect');
384
385     $limit = $maxrecords ? "LIMIT $maxrecords" : '';
386
387     $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
388     $limit .= " OFFSET $offset" if $offset;
389
390   }
391
392 }
393
394 #order by override
395 my $order_by = $opt{order_by} || '';
396 $order_by = $cgi->param('order_by') if $cgi->param('order_by');
397
398 # run the query
399
400 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
401 my $rows;
402
403 my @query;
404 if (ref($query) eq 'HASH') {
405   @query = $query;
406
407   if ( $order_by ) {
408     if ( $query->{'order_by'} ) {
409       if ( $query->{'order_by'} =~ /^(\s*ORDER\s+BY\s+)?(\S.*)$/is ) {
410         $query->{'order_by'} = "ORDER BY $order_by, $2";
411       } else {
412         warn "unparsable query order_by: ". $query->{'order_by'};
413         die "unparsable query order_by: ". $query->{'order_by'};
414       }
415     } else {
416       $query->{'order_by'} = "ORDER BY $order_by";
417     }
418   }
419
420   $query->{'order_by'} .= " $limit";
421
422 } elsif (ref($query) eq 'ARRAY') {
423   # do we still use this? it was for the old 477 report.
424   @query = @{ $query };
425 } else {
426   die "invalid query reference";
427 }
428
429 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
430   #%search = ( 'disabled' => '' );
431   $opt{'query'}->{'hashref'}->{'disabled'} = '';
432   $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
433 }
434
435 #eval "use FS::$opt{'query'};";
436 my @param = qw( select table addl_from hashref extra_sql order_by debug );
437 $rows = [ qsearch( [ map { my $query = $_;
438                            ({ map { $_ => $query->{$_} } @param });
439                          }
440                      @query
441                    ],
442                    #'order_by' => $opt{order_by}. " ". $limit,
443                  )
444         ]; 
445
446 # run the count query to get number of rows and other totals
447 my $count_sth = dbh->prepare($count_query);
448 $count_sth->execute
449   or die "Error executing '$count_query': ".$count_sth->errstr;
450 my $totals = $count_sth->fetchrow_arrayref;
451
452 push @$rows, $opt{'footer_data'} if $opt{'footer_data'};
453
454 </%init>