5 include( 'elements/search.html',
7 # basic options, required
8 'title' => 'Page title',
10 'name_singular' => 'item', #singular name for the records returned
11 #OR# # (preferred, will be pluralized automatically)
12 'name' => 'items', #plural name for the records returned
13 # (deprecated, will be singularlized
16 # some HTML callbacks...
17 'menubar' => '', #menubar arrayref
18 'html_init' => '', #after the header/menubar and before the pager
19 'html_form' => '', #after the pager, right before the results
20 # (only shown if there are results)
21 # (use this for any form-opening tag rather than
22 # html_init, to avoid a nested form)
23 'html_foot' => '', #at the bottom
24 'html_posttotal' => '', #at the bottom
25 # (these three can be strings or coderefs)
28 #literal SQL query string (deprecated?) or qsearch hashref, required
30 'table' => 'tablename',
31 #everything else is optional...
32 'hashref' => { 'field' => 'value',
33 'field' => { 'op' => '<',
38 'addl_from' => '', #'LEFT JOIN othertable USING ( key )',
39 'extra_sql' => '', #'AND otherstuff', #'WHERE onlystuff',
40 'order_by' => 'ORDER BY something',
43 # "select * from tablename";
45 #required unless 'query' is an SQL query string (shouldn't be...)
46 'count_query' => 'SELECT COUNT(*) FROM tablename',
48 'count_addl' => [], #additional count fields listref of sprintf strings
49 # [ $money_char.'%.2f total paid', ],
51 #listref of column labels, <TH>
52 #required unless 'query' is an SQL query string
53 # (if not specified the database column names will be used)
54 'header' => [ '#', 'Item' ],
56 'disable_download' => '', # set true to hide the CSV/Excel download links
57 'disable_nonefound' => '', # set true to disable the "No matching Xs found"
60 'disableable' => 1, # set true if this table has a "disabled" field, to
61 # hide disabled records & have "show disabled" links
62 'disabled_statuspos' => 3, #optional position (starting from 0) to insert
63 #a Status column when showing disabled records
64 #(query needs to be a qsearch hashref and
65 # header & fields need to be defined)
66 'agent_virt' => 1, # set true if this search should be agent-virtualized
67 'agent_null_right' => 'Access Right', #opt. right to view global records
68 'agent_pos' => 3, #optional position (starting from 0) to insert
70 #(query needs to be a qsearch hashref and
71 # header & fields need to be defined)
73 #listref - each item is a literal column name (or method) or coderef
74 #if not specified all columns will be shown
77 sub { my $row = shift; $row->column; },
80 #listref of column footers
83 #listref - each item is the empty string, or a listref of ...
87 'align' => 'lrc.', #one letter for each column, left/right/center/none
88 # can also pass a listref with full values:
89 # [ 'left', 'right', 'center', '' ]
92 #currently only HTML, maybe eventually Excel too
97 #redirect if there's only one item...
98 # listref of URL base and column name (or method)
99 # or a coderef that returns the same
102 #set to 1 (or column position for "disabled" status col) to enable
103 #"show disabled/hide disabled" links
104 #(can't be used with a literal query)
110 % if ( $type eq 'csv' ) {
112 % #http_header('Content-Type' => 'text/comma-separated-values' ); #IE chokes
113 % http_header('Content-Type' => 'text/plain' );
115 % my $csv = new Text::CSV_XS { 'always_quote' => 1,
116 % 'eol' => "\n", #"\015\012", #"\012"
119 % $csv->combine(@$header); #or die $csv->status;
124 % foreach my $row ( @$rows ) {
126 % if ( $opt{'fields'} ) {
130 % foreach my $field ( @{$opt{'fields'}} ) {
131 % if ( ref($field) eq 'CODE' ) {
134 % ? '(N/A)' #unimplemented
139 % push @line, $row->$field();
143 % $csv->combine(@line); #or die $csv->status;
146 % $csv->combine(@$row); #or die $csv->status;
155 % #} elsif ( $type eq 'excel' ) {
156 % } elsif ( $type =~ /\.xls$/ ) {
158 % #http_header('Content-Type' => 'application/excel' ); #eww
159 % http_header('Content-Type' => 'application/vnd.ms-excel' );
160 % #http_header('Content-Type' => 'application/msexcel' ); #alas
163 % my $XLS = new IO::Scalar \$data;
164 % my $workbook = Spreadsheet::WriteExcel->new($XLS)
165 % or die "Error opening .xls file: $!";
167 % my $worksheet = $workbook->add_worksheet(substr($opt{'title'},0,31));
171 % $worksheet->write($r, $c++, $_) foreach @$header;
173 % foreach my $row ( @$rows ) {
177 % if ( $opt{'fields'} ) {
179 % #my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
180 % #my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
182 % foreach my $field ( @{$opt{'fields'}} ) {
183 % #my $align = $aligns ? shift @$aligns : '';
184 % #$align = " ALIGN=$align" if $align;
187 % # my $link = shift @$links;
188 % # $link = &{$link}($row) if ref($link) eq 'CODE';
190 % # my( $url, $method ) = @{$link};
191 % # if ( ref($method) eq 'CODE' ) {
192 % # $a = $url. &{$method}($row);
194 % # $a = $url. $row->$method();
196 % # $a = qq(<A HREF="$a">);
199 % if ( ref($field) eq 'CODE' ) {
200 % foreach my $value ( &{$field}($row) ) {
201 % if ( ref($value) eq 'ARRAY' ) {
202 % $worksheet->write($r, $c++, '(N/A)' ); #unimplemented
204 % $worksheet->write($r, $c++, $value );
208 % $worksheet->write($r, $c++, $row->$field() );
213 % $worksheet->write($r, $c++, $_) foreach @$row;
218 % $workbook->close();# or die "Error creating .xls file: $!";
220 % http_header('Content-Length' => length($data) );
225 % } else { # regular HTML
227 % if ( exists($opt{'redirect'}) && scalar(@$rows) == 1 && $total == 1
228 % && $type ne 'html-print'
230 % my $redirect = $opt{'redirect'};
231 % $redirect = &{$redirect}($rows->[0]) if ref($redirect) eq 'CODE';
232 % my( $url, $method ) = @$redirect;
233 % redirect( $url. $rows->[0]->$method() );
235 % if ( $opt{'name_singular'} ) {
236 % $opt{'name'} = PL($opt{'name_singular'});
238 % ( my $xlsname = $opt{'name'} ) =~ s/\W//g;
239 % if ( $total == 1 ) {
240 % if ( $opt{'name_singular'} ) {
241 % $opt{'name'} = $opt{'name_singular'}
243 % #$opt{'name'} =~ s/s$// if $total == 1;
244 % $opt{'name'} =~ s/((s)e)?s$/$2/ if $total == 1;
248 % if ( $type eq 'html-print' ) {
250 <% include( '/elements/header-popup.html', $opt{'title'} ) %>
255 % if ( $opt{'menubar'} ) {
256 % @menubar = @{ $opt{'menubar'} };
258 % # @menubar = ( 'Main menu' => $p );
261 <% include( '/elements/header.html', $opt{'title'},
262 include( '/elements/menubar.html', @menubar )
266 <% defined($opt{'html_init'})
267 ? ( ref($opt{'html_init'})
268 ? &{$opt{'html_init'}}()
276 % unless ( $total ) {
277 % unless ( $opt{'disable_nonefound'} ) {
278 No matching <% $opt{'name'} %> found.<BR>
289 <% $total %> total <% $opt{'name'} %>
291 % if ( $confmax && $total > $confmax && $type ne 'html-print' ) {
292 % $cgi->delete('maxrecords');
293 % $cgi->param('_dummy', 1);
295 %# ( show <SELECT NAME="maxrecords" onChange="this.form.submit();">
296 ( show <SELECT NAME="maxrecords" onChange="window.location = '<% $cgi->self_url %>;maxrecords=' + this.options[this.selectedIndex].value;">
298 % foreach my $max ( map { $_ * $confmax } qw( 1 5 10 25 ) ) {
299 <OPTION VALUE="<% $max %>" <% ( $maxrecords == $max ) ? 'SELECTED' : '' %>><% $max %></OPTION>
304 % $cgi->param('maxrecords', $maxrecords);
307 % if ( defined($opt{'html_posttotal'}) && $type ne 'html-print' ) {
308 <% ref($opt{'html_posttotal'})
309 ? &{$opt{'html_posttotal'}}()
310 : $opt{'html_posttotal'}
315 % if ( $opt{'count_addl'} ) {
316 % my $n=0; foreach my $count ( @{$opt{'count_addl'}} ) {
317 <% sprintf( $count, $count_arrayref->[++$n] ) %><BR>
324 % unless ( $opt{'disable_download'} || $type eq 'html-print' ) {
328 Download full results<BR>
330 % $cgi->param('_type', "$xlsname.xls" );
331 as <A HREF="<% $cgi->self_url %>">Excel spreadsheet</A><BR>
333 % $cgi->param('_type', 'csv');
334 as <A HREF="<% $cgi->self_url %>">CSV file</A><BR>
336 % $cgi->param('_type', 'html-print');
337 as <A HREF="<% $cgi->self_url %>">printable copy</A>
340 % $cgi->param('_type', "html" );
348 % unless ( $type eq 'html_print' ) {
350 <% $pager = include( '/elements/pager.html',
352 'num_rows' => scalar(@$rows),
354 'maxrecords' => $maxrecords,
358 <% defined($opt{'html_form'})
359 ? ( ref($opt{'html_form'})
360 ? &{$opt{'html_form'}}()
368 <% include('/elements/table-grid.html') %>
371 % foreach my $header ( @$header ) {
372 <TH CLASS="grid" BGCOLOR="#cccccc"><% $header %></TH>
376 % my $bgcolor1 = '#eeeeee';
377 % my $bgcolor2 = '#ffffff';
380 % foreach my $row ( @$rows ) {
382 % if ( $bgcolor eq $bgcolor1 ) {
383 % $bgcolor = $bgcolor2;
385 % $bgcolor = $bgcolor1;
390 % if ( $opt{'fields'} ) {
392 % my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
393 % my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
394 % my $colors = $opt{'color'} ? [ @{$opt{'color'}} ] : [];
395 % my $sizes = $opt{'size'} ? [ @{$opt{'size'}} ] : [];
396 % my $styles = $opt{'style'} ? [ @{$opt{'style'}} ] : [];
398 % foreach my $field (
401 % if ( ref($_) eq 'ARRAY' ) {
405 % '<TABLE CLASS="inv" CELLSPACING=0 CELLPADDING=0 WIDTH="100%">'.
419 % uc($_).'="'. $e->{$_}. '"';
421 % grep exists($e->{$_}),
422 % qw( align bgcolor colspan rowspan
423 % style valign width )
428 % ? '<A HREF="'. $e->{'link'}. '">'
432 % ? '<FONT SIZE="'.uc($e->{'size'}).'">'
435 % ( $e->{'data_style'}
436 % ? '<'. uc($e->{'data_style'}). '>'
440 % ( $e->{'data_style'}
441 % ? '</'. uc($e->{'data_style'}). '>'
444 % ( $e->{'size'} ? '</FONT>' : '' ).
445 % ( $e->{'link'} ? '</A>' : '' ).
461 % if ( ref($_) eq 'CODE' ) {
471 % my $class = ( $field =~ /^<TABLE/i ) ? 'inv' : 'grid';
473 % my $align = $aligns ? shift @$aligns : '';
474 % $align = " ALIGN=$align" if $align;
478 % my $link = shift @$links;
479 % $link = &{$link}($row) if ref($link) eq 'CODE';
481 % my( $url, $method ) = @{$link};
482 % if ( ref($method) eq 'CODE' ) {
483 % $a = $url. &{$method}($row);
485 % $a = $url. $row->$method();
487 % $a = qq(<A HREF="$a">);
492 % my $color = shift @$colors;
493 % $color = &{$color}($row) if ref($color) eq 'CODE';
494 % my $size = shift @$sizes;
495 % $size = &{$size}($row) if ref($size) eq 'CODE';
496 % if ( $color || $size ) {
498 % ( $color ? "COLOR=#$color " : '' ).
499 % ( $size ? qq(SIZE="$size" ) : '' ).
503 % my($s, $es) = ( '', '' );
504 % my $style = shift @$styles;
505 % $style = &{$style}($row) if ref($style) eq 'CODE';
507 % $s = join( '', map "<$_>", split('', $style) );
508 % $es = join( '', map "</$_>", split('', $style) );
511 <TD CLASS="<% $class %>" BGCOLOR="<% $bgcolor %>"<% $align %>><% $font %><% $a %><% $s %><% $field %><% $es %><% $a ? '</A>' : '' %><% $font ? '</FONT>' : '' %></TD>
517 % foreach ( @$row ) {
518 <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $_ %></TD>
527 % if ( $opt{'footer'} ) {
531 % foreach my $footer ( @{ $opt{'footer'} } ) {
532 <TD CLASS="grid" BGCOLOR="#dddddd" STYLE="border-top: dashed 1px black;"><i><% $footer %></i></TD>
547 % if ( $type eq 'html-print' ) {
553 <% defined($opt{'html_foot'})
554 ? ( ref($opt{'html_foot'})
555 ? &{$opt{'html_foot'}}()
561 <% include( '/elements/footer.html' ) %>
571 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
573 my $curuser = $FS::CurrentUser::CurrentUser;
582 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
583 unless !$opt{align} || ref($opt{align});
585 if ( $opt{'agent_virt'} ) {
587 my $agentnums_sql = $curuser->agentnums_sql(
588 'null_right' => $opt{'agent_null_right'}
591 $opt{'query'}{'extra_sql'} .=
592 ( $opt{'query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
594 $opt{'count_query'} .=
595 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
598 if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
599 and scalar($curuser->agentnums) > 1 ) {
600 #false laziness w/statuspos above
601 my $pos = $opt{'agent_pos'};
603 foreach my $att (qw( align style color size )) {
604 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
607 splice @{ $opt{'header'} }, $pos, 0, 'Agent';
608 splice @{ $opt{'align'} }, $pos, 0, 'c';
609 splice @{ $opt{'style'} }, $pos, 0, '';
610 splice @{ $opt{'size'} }, $pos, 0, '';
611 splice @{ $opt{'fields'} }, $pos, 0,
612 sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
613 splice @{ $opt{'color'} }, $pos, 0, '';
614 splice @{ $opt{'links'} }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
621 if ( $opt{'disableable'} ) {
623 unless ( $cgi->param('showdisabled') ) { #modify searches
625 $opt{'query'}{'hashref'}{'disabled'} = '';
626 $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
628 $opt{'count_query'} .=
629 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
630 "( disabled = '' OR disabled IS NULL )";
632 } elsif ( $opt{'disabled_statuspos'}
633 || $opt{'disabled_statuspos'} eq '0' ) { #add status column
635 my $pos = $opt{'disabled_statuspos'};
637 foreach my $att (qw( align style color size )) {
638 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
641 splice @{ $opt{'header'} }, $pos, 0, 'Status';
642 splice @{ $opt{'align'} }, $pos, 0, 'c';
643 splice @{ $opt{'style'} }, $pos, 0, 'b';
644 splice @{ $opt{'size'} }, $pos, 0, '';
645 splice @{ $opt{'fields'} }, $pos, 0,
646 sub { shift->disabled ? 'DISABLED' : 'Active'; };
647 splice @{ $opt{'color'} }, $pos, 0,
648 sub { shift->disabled ? 'FF0000' : '00CC00'; };
649 splice @{ $opt{'links'} }, $pos, 0, ''
653 #add show/hide disabled links
654 my $items = $opt{'name'} || PL($opt{'name_singular'});
655 if ( $cgi->param('showdisabled') ) {
656 $cgi->param('showdisabled', 0);
657 $opt{'html_posttotal'} .=
658 '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!;
659 $cgi->param('showdisabled', 1);
661 $cgi->param('showdisabled', 1);
662 $opt{'html_posttotal'} .=
663 '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!;
664 $cgi->param('showdisabled', 0);
669 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|html(-print)?)$/
673 my($confmax, $maxrecords, $total, $offset, $count_arrayref);
675 unless ( $type =~ /^(csv|\w*\.xls)$/ ) {
677 unless (exists($opt{count_query}) && length($opt{count_query})) {
678 ( $opt{count_query} = $opt{query} ) =~
679 s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
682 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
684 ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
685 "( disabled = '' OR disabled IS NULL )";
688 unless ( $type eq 'html-print' ) {
690 #setup some pagination things if we're in html mode
692 my $conf = new FS::Conf;
693 $confmax = $conf->config('maxsearchrecordsperpage');
694 if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
697 $maxrecords ||= $confmax;
700 $limit = $maxrecords ? "LIMIT $maxrecords" : '';
702 $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
703 $limit .= " OFFSET $offset" if $offset;
707 my $count_sth = dbh->prepare($opt{'count_query'})
708 or die "Error preparing $opt{'count_query'}: ". dbh->errstr;
710 or die "Error executing $opt{'count_query'}: ". $count_sth->errstr;
711 $count_arrayref = $count_sth->fetchrow_arrayref;
712 $total = $count_arrayref->[0];
718 my $header = $opt{header};
720 if ( ref($opt{query}) ) {
722 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
723 #%search = ( 'disabled' => '' );
724 $opt{'query'}->{'hashref'}->{'disabled'} = '';
725 $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
728 #eval "use FS::$opt{'query'};";
730 'select' => $opt{'query'}->{'select'},
731 'table' => $opt{'query'}->{'table'},
732 'addl_from' => (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : ''),
733 'hashref' => $opt{'query'}->{'hashref'} || {},
734 'extra_sql' => $opt{'query'}->{'extra_sql'},
735 'order_by' => $opt{'query'}->{'order_by'}. " $limit",
738 my $sth = dbh->prepare("$opt{'query'} $limit")
739 or die "Error preparing $opt{'query'}: ". dbh->errstr;
741 or die "Error executing $opt{'query'}: ". $sth->errstr;
743 #can get # of rows without fetching them all?
744 $rows = $sth->fetchall_arrayref;
746 $header ||= $sth->{NAME};