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