add menu item and page for d/ling and edit rates with excel. RT#5108
[freeside.git] / httemplate / search / elements / search.html
1 <%doc>
2
3 Example:
4
5   include( '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
20     'query'       => {
21                        'table'     => 'tablename',
22                        #everything else is optional...
23                        'hashref'   => { 'field' => 'value',
24                                         'field' => { 'op'    => '<',
25                                                      'value' => '54',
26                                                    },
27                                       },
28                        'select'    => '*',
29                        'addl_from' => '', #'LEFT JOIN othertable USING ( key )',
30                        'extra_sql' => '', #'AND otherstuff', #'WHERE onlystuff',
31                        'order_by'  => 'ORDER BY something',
32    
33                      },
34                      # "select * from tablename";
35    
36     #required unless 'query' is an SQL query string (shouldn't be...)
37     'count_query' => 'SELECT COUNT(*) FROM tablename',
38
39     ###
40     # recommended / common
41     ###
42
43     #listref of column labels, <TH>
44     #recommended unless 'query' is an SQL query string
45     # (if not specified the database column names will be used)
46     'header'      => [ '#',
47                        'Item',
48                        { 'label' => 'Another Item',
49                          
50                        },
51                      ],
52
53     #listref - each item is a literal column name (or method) or coderef
54     #if not specified all columns will be shown
55     'fields'      => [
56                        'column',
57                        sub { my $row = shift; $row->column; },
58                      ],
59
60     #redirect if there's only one item...
61     # listref of URL base and column name (or method)
62     # or a coderef that returns the same
63     'redirect' => sub { my( $record, $cgi ) = @_;
64                         [ popurl(2).'view/item.html', 'primary_key' ];
65                       },
66
67     #redirect if there's no items
68     # scalar URL or a coderef that returns a URL
69     'redirect_empty' => sub { my( $cgi ) = @_;
70                               popurl(2).'view/item.html';
71                             },
72    
73     ###
74     # optional
75     ###
76    
77     # some HTML callbacks...
78     'menubar'          => '', #menubar arrayref
79     'html_init'        => '', #after the header/menubar and before the pager
80     'html_form'        => '', #after the pager, right before the results
81                               # (only shown if there are results)
82                               # (use this for any form-opening tag rather than
83                               #  html_init, to avoid a nested form)
84     'html_foot'        => '', #at the bottom
85     'html_posttotal'   => '', #at the bottom
86                               # (these three can be strings or coderefs)
87     
88     'count_addl' => [], #additional count fields listref of sprintf strings or coderefs
89                         # [ $money_char.'%.2f total paid', ],
90    
91     #second (smaller) header line, currently only for HTML
92     'header2      => [ '#',
93                        'Item',
94                        { 'label' => 'Another Item',
95                          
96                        },
97                      ],
98
99     #listref of column footers
100     'footer'      => [],
101     
102     #disabling things
103     'disable_download'  => '', # set true to hide the CSV/Excel download links
104     'disable_total'     => '', # set true to hide the total"
105     'disable_maxselect' => '', # set true to disable record/page selection
106     'disable_nonefound' => '', # set true to disable the "No matching Xs found"
107                                # message
108    
109     #handling "disabled" fields in the records
110     'disableable' => 1,  # set set to 1 (or column position for "disabled"
111                          # status col) to enable if this table has a "disabled"
112                          # field, to hide disabled records & have
113                          # "show disabled/hide disabled" links
114                          #(can't be used with a literal query)
115     'disabled_statuspos' => 3, #optional position (starting from 0) to insert
116                                #a Status column when showing disabled records
117                                #(query needs to be a qsearch hashref and
118                                # header & fields need to be defined)
119
120     #handling agent virtualization
121     'agent_virt'            => 1, # set true if this search should be
122                                   # agent-virtualized
123     'agent_null_right'      => 'Access Right', # optional right to view global
124                                                # records
125     'agent_null_right_link' => 'Access Right'  # optional right to link to
126                                                # global records; defaults to
127                                                # same as agent_null_right
128     'agent_pos'             => 3, # optional position (starting from 0) to
129                                   # insert an Agent column (query needs to be a
130                                   # qsearch hashref and header & fields need to
131                                   # be defined)
132
133     # link & display properties for fields
134    
135     #listref - each item is the empty string,
136     #          or a listref of link and method name to append,
137     #          or a listref of link and coderef to run and append
138     #          or a coderef that returns such a listref
139     'links'       => [],`
140
141     #listref - each item is the empty string,
142     #          or a string onClick handler for the corresponding link
143     #          or a coderef that returns string onClick handler
144     'link_onclicks' => [],
145
146     #one letter for each column, left/right/center/none
147     # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
148     'align'       => 'lrc.',
149    
150     #listrefs of ( scalars or coderefs )
151     # currently only HTML, maybe eventually Excel too
152     'color'       => [],
153     'size'        => [],
154     'style'       => [], #<B> or <I>, etc.
155     'cell_style'  => [], #STYLE= attribute of TR, very HTML-specific...
156
157     # Excel-specific listref of ( hashrefs or coderefs )
158     # each hashref: http://search.cpan.org/dist/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm#Format_methods_and_Format_properties
159     'xls_format' => => [],
160     
161   );
162
163 </%doc>
164 % if ( $type eq 'csv' ) {
165 %
166 <% include('search-csv.html',  header=>$header, rows=>$rows, opt=>\%opt ) %>
167 %
168 % #} elsif ( $type eq 'excel' ) {
169 % } elsif ( $type =~ /\.xls$/ ) {
170 %
171 <% include('search-xls.html',  header=>$header, rows=>$rows, opt=>\%opt ) %>
172 %
173 % } else { # regular HTML
174 %
175 <% include('search-html.html',
176              type           => $type,
177              header         => $header,
178              rows           => $rows,
179              link_agentnums => \@link_agentnums,
180              null_link      => $null_link,
181              confmax        => $confmax,
182              maxrecords     => $maxrecords,
183              offset         => $offset,
184              opt            => \%opt
185           )
186 %>
187 %
188 % } 
189 <%init>
190
191 my(%opt) = @_;
192 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
193
194 my $curuser = $FS::CurrentUser::CurrentUser;
195
196 my %align = (
197   'l' => 'left',
198   'r' => 'right',
199   'c' => 'center',
200   ' ' => '',
201   '.' => '',
202 );
203 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
204   unless !$opt{align} || ref($opt{align});
205
206 $opt{disable_download} = 0
207   if $opt{disable_download} && $curuser->access_right('Configuration download');
208
209 my @link_agentnums = ();
210 my $null_link = '';
211 if ( $opt{'agent_virt'} ) {
212
213   @link_agentnums = $curuser->agentnums;
214   $null_link = $curuser->access_right(    $opt{'agent_null_right_link'}
215                                        || $opt{'agent_null_right'}      );
216
217   my $agentnums_sql = $curuser->agentnums_sql(
218                         'null_right' => $opt{'agent_null_right'}
219                       );
220
221   $opt{'query'}{'extra_sql'} .=
222     ( $opt{'query'}{'extra_sql'} =~ /WHERE/i || keys %{$opt{'query'}{'hashref'}}
223       ? ' AND '
224       : ' WHERE ' ). $agentnums_sql;
225
226   $opt{'count_query'} .=
227     ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).  $agentnums_sql;
228
229   if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
230        and scalar($curuser->agentnums) > 1           ) {
231     #false laziness w/statuspos above
232     my $pos = $opt{'agent_pos'};
233
234     foreach my $att (qw( align color size style cell_style xls_format )) {
235       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
236     }
237
238     splice @{ $opt{'header'} }, $pos, 0, 'Agent'; 
239     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
240     splice @{ $opt{'style'}  }, $pos, 0, ''; 
241     splice @{ $opt{'size'}   }, $pos, 0, ''; 
242     splice @{ $opt{'fields'} }, $pos, 0,
243       sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
244     splice @{ $opt{'color'}  }, $pos, 0, '';
245     splice @{ $opt{'links'}  }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
246       if $opt{'links'};
247     splice @{ $opt{'link_onclicks'}  }, $pos, 0, ''
248       if $opt{'link_onclicks'};
249
250   }
251
252 }
253
254 if ( $opt{'disableable'} ) {
255
256   unless ( $cgi->param('showdisabled') ) { #modify searches
257
258     $opt{'query'}{'hashref'}{'disabled'} = '';
259     $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
260
261     $opt{'count_query'} .=
262       ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
263       "( disabled = '' OR disabled IS NULL )";
264
265   } elsif (    $opt{'disabled_statuspos'}
266             || $opt{'disabled_statuspos'} eq '0' ) { #add status column
267
268     my $pos = $opt{'disabled_statuspos'};
269
270     foreach my $att (qw( align style color size )) {
271       $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
272     }
273
274     splice @{ $opt{'header'} }, $pos, 0, 'Status'; 
275     splice @{ $opt{'align'}  }, $pos, 0, 'c'; 
276     splice @{ $opt{'style'}  }, $pos, 0, 'b'; 
277     splice @{ $opt{'size'}   }, $pos, 0, ''; 
278     splice @{ $opt{'fields'} }, $pos, 0,
279       sub { shift->disabled ? 'DISABLED' : 'Active'; };
280     splice @{ $opt{'color'}  }, $pos, 0,
281       sub { shift->disabled ? 'FF0000'   : '00CC00'; };
282     splice @{ $opt{'links'}  }, $pos, 0, ''
283       if $opt{'links'};
284     splice @{ $opt{'link_onlicks'}  }, $pos, 0, ''
285       if $opt{'link_onlicks'};
286   }
287
288   #add show/hide disabled links
289   my $items = $opt{'name'} || PL($opt{'name_singular'});
290   if ( $cgi->param('showdisabled') ) {
291     $cgi->param('showdisabled', 0);
292     $opt{'html_posttotal'} .=
293       '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!;
294     $cgi->param('showdisabled', 1);
295   } else {
296     $cgi->param('showdisabled', 1);
297     $opt{'html_posttotal'} .=
298       '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!;
299     $cgi->param('showdisabled', 0);
300   }
301
302 }
303
304 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|select|html(-print)?)$/
305            ? $1 : 'html';
306
307 my $limit = '';
308 my($confmax, $maxrecords, $offset );
309
310 unless ( $type =~ /^(csv|\w*\.xls)$/ ) {
311
312   unless (exists($opt{count_query}) && length($opt{count_query})) {
313     ( $opt{count_query} = $opt{query} ) =~
314       s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
315   }
316
317   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
318     $opt{count_query} .=
319       ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
320       "( disabled = '' OR disabled IS NULL )";
321   }
322
323   unless ( $type eq 'html-print' ) {
324
325     #setup some pagination things if we're in html mode
326
327     my $conf = new FS::Conf;
328     $confmax = $conf->config('maxsearchrecordsperpage');
329     if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
330       $maxrecords = $1;
331     } else {
332       $maxrecords ||= $confmax;
333     }
334
335     $limit = $maxrecords ? "LIMIT $maxrecords" : '';
336
337     $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
338     $limit .= " OFFSET $offset" if $offset;
339
340   }
341
342 }
343
344 # run the query
345
346 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
347 my $rows;
348 if ( ref($opt{query}) ) {
349
350   if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
351     #%search = ( 'disabled' => '' );
352     $opt{'query'}->{'hashref'}->{'disabled'} = '';
353     $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
354   }
355
356   #eval "use FS::$opt{'query'};";
357   $rows = [ qsearch({
358     'select'    => $opt{'query'}->{'select'},
359     'table'     => $opt{'query'}->{'table'}, 
360     'addl_from' => (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : ''),
361     'hashref'   => $opt{'query'}->{'hashref'} || {}, 
362     'extra_sql' => $opt{'query'}->{'extra_sql'},
363     'order_by'  => $opt{'query'}->{'order_by'}. " $limit",
364   }) ];
365 } else {
366   my $sth = dbh->prepare("$opt{'query'} $limit")
367     or die "Error preparing $opt{'query'}: ". dbh->errstr;
368   $sth->execute
369     or die "Error executing $opt{'query'}: ". $sth->errstr;
370
371   #can get # of rows without fetching them all?
372   $rows = $sth->fetchall_arrayref;
373
374   $header ||= $sth->{NAME};
375 }
376
377 </%init>