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