start of package class web UI (add/edit package classes, package class selection...
[freeside.git] / httemplate / search / elements / search.html
1 <%
2
3   # options example...  
4   # (everything not commented required is optional)
5   #
6   # # basic options, required
7   # 'title'       => 'Page title',
8   # 'name'        => 'items', #name for the records returned
9   #
10   # # some HTML callbacks...
11   # 'menubar'          => '', #menubar arrayref
12   # 'html_init'        => '', #after the header/menubar and before the pager
13   # 'html_foot'        => '', #at the bottom
14   # 'html_posttotal'   => '', #at the bottom
15   #                           # (these three can be strings or coderefs)
16   # 
17   #
18   # #literal SQL query string or qsearch hashref, required
19   # 'query'       => {
20   #                    'table'     => 'tablename',
21   #                    #everything else is optional...
22   #                    'hashref'   => { 'field' => 'value',
23   #                                     'field' => { 'op'    => '<',
24   #                                                  'value' => '54',
25   #                                                },
26   #                                   },
27   #                    'select'    => '*',
28   #                    'addl_from' => '', #'LEFT JOIN othertable USING ( key )',
29   #                    'extra_sql' => '', #'AND otherstuff', #'WHERE onlystuff',
30   #                    
31   #
32   #                  },
33   #                  # "select * from tablename";
34   #
35   # #required unless 'query' is an SQL query string (shouldn't be...)
36   # 'count_query' => 'SELECT COUNT(*) FROM tablename',
37   #
38   # 'count_addl' => [], #additional count fields listref of sprintf strings
39   #                     # [ $money_char.'%.2f total paid', ],
40   #
41   # #listref of column labels, <TH>
42   # #required unless 'query' is an SQL query string
43   # # (if not specified the database column names will be used)
44   # 'header'      => [ '#', 'Item' ],
45   #
46   # 'disable_download' => '', # set true to hide the CSV/Excel download links
47   # 'disable_nonefound' => '', # set true to disable the "No matching Xs found"
48   #                            # message
49   #
50   # #listref - each item is a literal column name (or method) or coderef
51   # #if not specified all columns will be shown
52   # 'fields'      => [
53   #                    'column',
54   #                    sub { my $row = shift; $row->column; },
55   #                  ],
56   #
57   # #listref of column footers
58   # 'footer'      => [],
59   # 
60   # #listref - each item is the empty string, or a listref of ...
61   # 'links'       =>
62   #
63   #
64   # 'align'       => 'lrc.', #one letter for each column, left/right/center/none
65   #                          # can also pass a listref with full values:
66   #                          # [ 'left', 'right', 'center', '' ]
67   #
68   # #listrefs...
69   # #currently only HTML, maybe eventually Excel too
70   # 'color'       => [],
71   # 'size'        => [],
72   # 'style'       => [],
73   # 
74   # #redirect if there's only one item...
75   # # listref of URL base and column name (or method)
76   # # or a coderef that returns the same
77   # 'redirect' =>
78
79   my $DEBUG = 0;
80
81   my(%opt) = @_;
82   #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
83
84   my %align = (
85     'l' => 'left',
86     'r' => 'right',
87     'c' => 'center',
88     ' ' => '',
89     '.' => '',
90   );
91   $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
92     unless !$opt{align} || ref($opt{align});
93
94   my $type = '';
95   my $limit = '';
96   my($maxrecords, $total, $offset, $count_arrayref);
97
98   if ( $cgi->param('_type') =~ /^(csv|\w*\.xls)$/ ) {
99   
100     $type = $1;
101
102   } else { #setup some pagination things if we're in html mode
103
104     unless (exists($opt{'count_query'}) && length($opt{'count_query'})) {
105       ( $opt{'count_query'} = $opt{'query'} ) =~
106         s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i;
107     }
108
109     my $conf = new FS::Conf;
110     $maxrecords = $conf->config('maxsearchrecordsperpage');
111
112     $limit = $maxrecords ? "LIMIT $maxrecords" : '';
113
114     $offset = $cgi->param('offset') || 0;
115     $limit .= " OFFSET $offset" if $offset;
116
117     my $count_sth = dbh->prepare($opt{'count_query'})
118       or die "Error preparing $opt{'count_query'}: ". dbh->errstr;
119     $count_sth->execute
120       or die "Error executing $opt{'count_query'}: ". $count_sth->errstr;
121     $count_arrayref = $count_sth->fetchrow_arrayref;
122     $total = $count_arrayref->[0];
123
124   }
125
126   # run the query
127
128   my $header = $opt{'header'};
129   my $rows;
130   if ( ref($opt{'query'}) ) {
131
132     #eval "use FS::$opt{'query'};";
133     $rows = [ qsearch(
134       $opt{'query'}->{'table'}, 
135       $opt{'query'}->{'hashref'} || {}, 
136       $opt{'query'}->{'select'},
137       $opt{'query'}->{'extra_sql'}. " $limit",
138       '',
139       (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : '')
140     ) ];
141
142   } else {
143
144     my $sth = dbh->prepare("$opt{'query'} $limit")
145       or die "Error preparing $opt{'query'}: ". dbh->errstr;
146     $sth->execute
147       or die "Error executing $opt{'query'}: ". $sth->errstr;
148
149     #can get # of rows without fetching them all?
150     $rows = $sth->fetchall_arrayref;
151
152     $header ||= $sth->{NAME};
153
154   }
155
156   warn scalar(@$rows). ' rows returned from '.
157        ( ref($opt{'query'}) ? 'qsearch query' : 'literal SQL query' )
158     if $DEBUG || $opt{'debug'};
159
160   # display the results - csv, xls or html
161
162   if ( $type eq 'csv' ) {
163
164     #http_header('Content-Type' => 'text/comma-separated-values' ); #IE chokes
165     http_header('Content-Type' => 'text/plain' );
166
167     my $csv = new Text::CSV_XS { 'always_quote' => 1,
168                                  'eol'          => "\n", #"\015\012", #"\012"
169                                };
170
171     $csv->combine(@$header); #or die $csv->status;
172     %><%= $csv->string %><%
173
174     foreach my $row ( @$rows ) {
175
176       if ( $opt{'fields'} ) {
177
178         my @line = ();
179
180         foreach my $field ( @{$opt{'fields'}} ) {
181           if ( ref($field) eq 'CODE' ) {
182             push @line, map {
183                               ref($_) eq 'ARRAY'
184                                 ? '(N/A)' #unimplemented
185                                 : $_;
186                             }
187                             &{$field}($row);
188           } else {
189             push @line, $row->$field();
190           }
191         }
192
193         $csv->combine(@line); #or die $csv->status;
194
195       } else {
196         $csv->combine(@$row); #or die $csv->status;
197       }
198
199       %><%= $csv->string %><%
200
201     }
202
203   #} elsif ( $type eq 'excel' ) {
204   } elsif ( $type =~ /\.xls$/ ) {
205
206     #http_header('Content-Type' => 'application/excel' ); #eww
207     http_header('Content-Type' => 'application/vnd.ms-excel' );
208     #http_header('Content-Type' => 'application/msexcel' ); #alas
209
210     my $data = '';
211     my $XLS = new IO::Scalar \$data;
212     my $workbook = Spreadsheet::WriteExcel->new($XLS)
213       or die "Error opening .xls file: $!";
214
215     my $worksheet = $workbook->add_worksheet(substr($opt{'title'},0,31));
216
217     my($r,$c) = (0,0);
218
219     $worksheet->write($r, $c++, $_) foreach @$header;
220
221     foreach my $row ( @$rows ) {
222       $r++;
223       $c = 0;
224
225       if ( $opt{'fields'} ) {
226
227         #my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
228         #my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
229
230         foreach my $field ( @{$opt{'fields'}} ) {
231           #my $align = $aligns ? shift @$aligns : '';
232           #$align = " ALIGN=$align" if $align;
233           #my $a = '';
234           #if ( $links ) {
235           #  my $link = shift @$links;
236           #  $link = &{$link}($row) if ref($link) eq 'CODE';
237           #  if ( $link ) {
238           #    my( $url, $method ) = @{$link};
239           #    if ( ref($method) eq 'CODE' ) {
240           #      $a = $url. &{$method}($row);
241           #    } else {
242           #      $a = $url. $row->$method();
243           #    }
244           #    $a = qq(<A HREF="$a">);
245           #  }
246           #}
247           if ( ref($field) eq 'CODE' ) {
248             foreach my $value ( &{$field}($row) ) {
249               if ( ref($value) eq 'ARRAY' ) { 
250                 $worksheet->write($r, $c++, '(N/A)' ); #unimplemented
251               } else {
252                 $worksheet->write($r, $c++, $value );
253               }
254             }
255           } else {
256             $worksheet->write($r, $c++, $row->$field() );
257           }
258         }
259
260       } else {
261         $worksheet->write($r, $c++, $_) foreach @$row;
262       }
263
264     }
265
266     $workbook->close();# or die "Error creating .xls file: $!";
267
268     http_header('Content-Length' => length($data) );
269     %><%= $data %><%
270
271   } else { # regular HTML
272
273     if ( exists($opt{'redirect'}) && scalar(@$rows) == 1 && $total == 1 ) {
274       my $redirect = $opt{'redirect'};
275       $redirect = &{$redirect}($rows->[0]) if ref($redirect) eq 'CODE';
276       my( $url, $method ) = @$redirect;
277       redirect( $url. $rows->[0]->$method() );
278     } else {
279       ( my $xlsname = $opt{'name'} ) =~ s/\W//g;
280       #$opt{'name'} =~ s/s$// if $total == 1;
281       $opt{'name'} =~ s/((s)e)?s$/$2/ if $total == 1;  #should use Lingua::bs
282                                                        # to "depluralize"
283
284       my @menubar = ();
285       if ( $opt{'menubar'} ) {
286         @menubar = @{ $opt{'menubar'} };
287       } else {
288         @menubar = ( 'Main menu' => $p );
289       }
290
291
292   %>
293   <%= include( '/elements/header.html', $opt{'title'},
294                  include( '/elements/menubar.html', @menubar )
295              )
296   %>
297   <%= defined($opt{'html_init'}) 
298         ? ( ref($opt{'html_init'})
299               ? &{$opt{'html_init'}}()
300               : $opt{'html_init'}
301           )
302         : ''
303   %>
304   <% my $pager = include ( '/elements/pager.html',
305                              'offset'     => $offset,
306                              'num_rows'   => scalar(@$rows),
307                              'total'      => $total,
308                              'maxrecords' => $maxrecords,
309                          );
310   %>
311   <% unless ( $total ) { %>
312     <% unless ( $opt{'disable_nonefound'} ) { %>
313       No matching <%= $opt{'name'} %> found.<BR>
314     <% } %>
315   <% } else { %>
316   
317     <TABLE>
318       <TR>
319         <TD VALIGN="bottom">
320           <%= $total %> total <%= $opt{'name'} %>
321           <%= defined($opt{'html_posttotal'}) 
322                 ? ( ref($opt{'html_posttotal'})
323                       ? &{$opt{'html_posttotal'}}()
324                       : $opt{'html_posttotal'}
325                   )
326                 : ''
327           %>
328           <BR>
329           <% if ( $opt{'count_addl'} ) { %>
330             <% my $n=0; foreach my $count ( @{$opt{'count_addl'}} ) { %>
331               <%= sprintf( $count, $count_arrayref->[++$n] ) %><BR>
332             <% } %>
333           <% } %>
334         </TD>
335         <% unless ( $opt{'disable_download'} ) { %>
336           <TD ALIGN="right">
337             <% $cgi->param('_type', "$xlsname.xls" ); %>
338             Download full results<BR>
339             as <A HREF="<%= $cgi->self_url %>">Excel spreadsheet</A><BR>
340             <% $cgi->param('_type', 'csv'); %>
341             as <A HREF="<%= $cgi->self_url %>">CSV file</A>
342           </TD>
343         <% } %>
344       </TR>
345       <TR>
346         <TD COLSPAN=2>
347             <%= $pager %>
348
349             <%= include('/elements/table-grid.html') %>
350
351               <TR>
352               <% 
353                  foreach my $header ( @$header ) { %>
354                    <TH CLASS="grid" BGCOLOR="#cccccc"><%= $header %></TH>
355               <% } %>
356               </TR>
357               <% my $bgcolor1 = '#eeeeee';
358                  my $bgcolor2 = '#ffffff';
359                  my $bgcolor;
360                  foreach my $row ( @$rows ) {
361                    if ( $bgcolor eq $bgcolor1 ) {
362                      $bgcolor = $bgcolor2;
363                    } else {
364                      $bgcolor = $bgcolor1;
365                    }
366               %>
367                    <TR>
368                    <% if ( $opt{'fields'} ) {
369
370                         my $links  = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
371                         my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
372                         my $colors = $opt{'color'} ? [ @{$opt{'color'}} ] : [];
373                         my $sizes  = $opt{'size'}  ? [ @{$opt{'size'}}  ] : [];
374                         my $styles = $opt{'style'} ? [ @{$opt{'style'}} ] : [];
375
376                         foreach my $field (
377
378                           map {
379                                 if ( ref($_) eq 'ARRAY' ) {
380
381                                   my $tableref = $_;
382
383                                   '<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0'.
384                                   ' STYLE="border:none">'.
385
386                                   join('', map {
387
388                                     my $rowref = $_;
389
390                                     '<tr>'.
391
392                                     join('', map {
393
394                                       my $element = $_;
395
396                                       '<TD STYLE="border:none"'.
397                                       ( $element->{'align'}
398                                           ? ' ALIGN="'. $element->{'align'}. '"'
399                                           : ''
400                                       ). '>'.
401                                       ( $element->{'link'}
402                                           ? '<A HREF="'. $element->{'link'}.'">'
403                                           : ''
404                                       ).
405                                       $element->{'data'}.
406                                       ( $element->{'link'}
407                                           ? '</A>'
408                                           : ''
409                                       ).
410                                       '</td>';
411
412                                     } @$rowref ).
413
414                                     '</tr>';
415                                   } @$tableref ).
416
417                                   '</table>';
418
419                                 } else {
420                                   $_;
421                                 }
422                               }
423
424                           map {
425                                 if ( ref($_) eq 'CODE' ) {
426                                   &{$_}($row);
427                                 } else {
428                                   $row->$_();
429                                 }
430                               }
431                           @{$opt{'fields'}}
432
433                         ) {
434
435                           my $align = $aligns ? shift @$aligns : '';
436                           $align = " ALIGN=$align" if $align;
437
438                           my $a = '';
439                           if ( $links ) {
440                             my $link = shift @$links;
441                             $link = &{$link}($row) if ref($link) eq 'CODE';
442                             if ( $link ) {
443                               my( $url, $method ) = @{$link};
444                               if ( ref($method) eq 'CODE' ) {
445                                 $a = $url. &{$method}($row);
446                               } else {
447                                 $a = $url. $row->$method();
448                               }
449                               $a = qq(<A HREF="$a">);
450                             }
451                           }
452
453                           my $font = '';
454                           my $color = shift @$colors;
455                           $color = &{$color}($row) if ref($color) eq 'CODE';
456                           my $size = shift @$sizes;
457                           $size = &{$size}($row) if ref($size) eq 'CODE';
458                           if ( $color || $size ) {
459                             $font = '<FONT '.
460                                     ( $color ? "COLOR=#$color "   : '' ).
461                                     ( $size  ? qq(SIZE="$size" )  : '' ).
462                                     '>';
463                           }
464
465                           my($s, $es) = ( '', '' );
466                           my $style = shift @$styles;
467                           $style = &{$style}($row) if ref($style) eq 'CODE';
468                           if ( $style ) {
469                             $s = join( '', map "<$_>", split('', $style) );
470                             $es = join( '', map "</$_>", split('', $style) );
471                           }
472
473                        %>
474                        <TD CLASS="grid" BGCOLOR="<%= $bgcolor %>"<%= $align %>><%= $font %><%= $a %><%= $s %><%= $field %><%= $es %><%= $a ? '</A>' : '' %><%= $font ? '</FONT>' : '' %></TD>
475                      <% } %>
476                    <% } else { %>
477                      <% foreach ( @$row ) { %>
478                           <TD CLASS="grid" BGCOLOR="<%= $bgcolor %>"><%= $_ %></TD>
479                      <% } %>
480                    <% } %>
481                    </TR>
482               <% } %>
483
484               <% if ( $opt{'footer'} ) { %>
485                 <TR>
486                 <% foreach my $footer ( @{ $opt{'footer'} } ) { %>
487                      <TD CLASS="grid" BGCOLOR="#dddddd" STYLE="border-top: dashed 1px black;"><i><%= $footer %></i></TH>
488                 <% } %>
489                 </TR>
490               <% } %>
491             
492             </TABLE>
493             <%= $pager %>
494   
495           </TD>
496         </TR>
497       </TABLE>
498   
499   <% } %>
500   <%= defined($opt{'html_foot'}) 
501         ? ( ref($opt{'html_foot'})
502               ? &{$opt{'html_foot'}}()
503               : $opt{'html_foot'}
504           )
505         : ''
506   %>
507   <%= include( '/elements/footer.html' ) %>
508   <% } %>
509 <% } %>