5 include( 'elements/search.html',
11 'title' => 'Page title',
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
19 #literal SQL query string (deprecated?) or qsearch hashref
21 'table' => 'tablename',
22 #everything else is optional...
23 'hashref' => { 'field' => 'value',
24 'field' => { 'op' => '<',
29 'addl_from' => '', #'LEFT JOIN othertable USING ( key )',
30 'extra_sql' => '', #'AND otherstuff', #'WHERE onlystuff',
31 'order_by' => 'ORDER BY something',
34 # "select * from tablename";
36 #required unless 'query' is an SQL query string (shouldn't be...)
37 'count_query' => 'SELECT COUNT(*) FROM tablename',
40 # recommended / common
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)
48 { 'label' => 'Another Item',
53 #listref - each item is a literal column name (or method) or coderef
54 #if not specified all columns will be shown
57 sub { my $row = shift; $row->column; },
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' ];
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';
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)
88 'count_addl' => [], #additional count fields listref of sprintf strings or coderefs
89 # [ $money_char.'%.2f total paid', ],
91 #second (smaller) header line, currently only for HTML
94 { 'label' => 'Another Item',
99 #listref of column footers
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"
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)
120 #handling agent virtualization
121 'agent_virt' => 1, # set true if this search should be
123 'agent_null_right' => 'Access Right', # optional right to view global
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
133 # link & display properties for fields
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
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' => [],
146 #one letter for each column, left/right/center/none
147 # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
150 #listrefs of ( scalars or coderefs )
151 #currently only HTML, maybe eventually Excel too
154 'style' => [], #<B> or <I>, etc.
155 'cell_style' => [], #STYLE= attribute of TR, very HTML-specific...
160 % if ( $type eq 'csv' ) {
162 % #http_header('Content-Type' => 'text/comma-separated-values' ); #IE chokes
163 % http_header('Content-Type' => 'text/plain' );
165 % my $csv = new Text::CSV_XS { 'always_quote' => 1,
166 % 'eol' => "\n", #"\015\012", #"\012"
169 % $csv->combine(@$header); #or die $csv->status;
174 % foreach my $row ( @$rows ) {
176 % if ( $opt{'fields'} ) {
180 % foreach my $field ( @{$opt{'fields'}} ) {
181 % if ( ref($field) eq 'CODE' ) {
184 % ? '(N/A)' #unimplemented
189 % push @line, $row->$field();
193 % $csv->combine(@line); #or die $csv->status;
196 % $csv->combine(@$row); #or die $csv->status;
205 % #} elsif ( $type eq 'excel' ) {
206 % } elsif ( $type =~ /\.xls$/ ) {
208 % #http_header('Content-Type' => 'application/excel' ); #eww
209 % #http_header('Content-Type' => 'application/msexcel' ); #alas
210 % #http_header('Content-Type' => 'application/x-msexcel' ); #?
212 % #http://support.microsoft.com/kb/199841
213 % http_header('Content-Type' => 'application/vnd.ms-excel' );
215 % #http://support.microsoft.com/kb/812935
216 % #http://support.microsoft.com/kb/323308
217 % $HTML::Mason::Commands::r->headers_out->{'Cache-control'} = 'max-age=0';
220 % my $XLS = new IO::Scalar \$data;
221 % my $workbook = Spreadsheet::WriteExcel->new($XLS)
222 % or die "Error opening .xls file: $!";
224 % my $worksheet = $workbook->add_worksheet(substr($opt{'title'},0,31));
228 % $worksheet->write($r, $c++, $_) foreach @$header;
230 % foreach my $row ( @$rows ) {
234 % if ( $opt{'fields'} ) {
236 % #my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
237 % #my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
239 % foreach my $field ( @{$opt{'fields'}} ) {
240 % #my $align = $aligns ? shift @$aligns : '';
241 % #$align = " ALIGN=$align" if $align;
244 % # my $link = shift @$links;
245 % # $link = &{$link}($row) if ref($link) eq 'CODE';
247 % # my( $url, $method ) = @{$link};
248 % # if ( ref($method) eq 'CODE' ) {
249 % # $a = $url. &{$method}($row);
251 % # $a = $url. $row->$method();
253 % # $a = qq(<A HREF="$a">);
256 % if ( ref($field) eq 'CODE' ) {
257 % foreach my $value ( &{$field}($row) ) {
258 % if ( ref($value) eq 'ARRAY' ) {
259 % $worksheet->write($r, $c++, '(N/A)' ); #unimplemented
261 % $worksheet->write($r, $c++, $value );
265 % $worksheet->write($r, $c++, $row->$field() );
270 % $worksheet->write($r, $c++, $_) foreach @$row;
275 % $workbook->close();# or die "Error creating .xls file: $!";
277 % http_header('Content-Length' => length($data) );
282 % } else { # regular HTML
284 % if ( exists($opt{'redirect'}) && scalar(@$rows) == 1 && $total == 1
285 % && $type ne 'html-print'
287 % my $redirect = $opt{'redirect'};
288 % $redirect = &{$redirect}($rows->[0], $cgi) if ref($redirect) eq 'CODE';
289 % my( $url, $method ) = @$redirect;
290 % redirect( $url. $rows->[0]->$method() );
291 % } elsif ( exists($opt{'redirect_empty'}) && ! scalar(@$rows) && $total == 0
292 % && $type ne 'html-print'
293 % && $opt{'redirect_empty'}
294 % && ( ref($opt{'redirect_empty'}) ne 'CODE'
295 % || &{$opt{'redirect_empty'}}($cgi) )
297 % my $redirect = $opt{'redirect_empty'};
298 % $redirect = &{$redirect}($cgi) if ref($redirect) eq 'CODE';
299 % redirect( $redirect );
301 % if ( $opt{'name_singular'} ) {
302 % $opt{'name'} = PL($opt{'name_singular'});
304 % ( my $xlsname = $opt{'name'} ) =~ s/\W//g;
305 % if ( $total == 1 ) {
306 % if ( $opt{'name_singular'} ) {
307 % $opt{'name'} = $opt{'name_singular'}
309 % #$opt{'name'} =~ s/s$// if $total == 1;
310 % $opt{'name'} =~ s/((s)e)?s$/$2/ if $total == 1;
314 % if ( $type eq 'html-print' ) {
316 <% include( '/elements/header-popup.html', $opt{'title'} ) %>
318 % } elsif ( $type eq 'select' ) {
320 <% include( '/elements/header-popup.html', $opt{'title'} ) %>
321 <% defined($opt{'html_init'})
322 ? ( ref($opt{'html_init'})
323 ? &{$opt{'html_init'}}()
332 % if ( $opt{'menubar'} ) {
333 % @menubar = @{ $opt{'menubar'} };
335 % # @menubar = ( 'Main menu' => $p );
338 <% include( '/elements/header.html', $opt{'title'},
339 include( '/elements/menubar.html', @menubar )
343 <% defined($opt{'html_init'})
344 ? ( ref($opt{'html_init'})
345 ? &{$opt{'html_init'}}()
353 % unless ( $total ) {
354 % unless ( $opt{'disable_nonefound'} ) {
355 No matching <% $opt{'name'} %> found.<BR>
359 % if ( $total || $opt{'disableable'} ) { #hmm... and there *are* ones to show??
368 % if (! $opt{'disable_total'}) {
369 <% $total %> total <% $opt{'name'} %>
372 % if ( $confmax && $total > $confmax
373 % && ! $opt{'disable_maxselect'}
374 % && $type ne 'html-print' )
376 % $cgi->delete('maxrecords');
377 % $cgi->param('_dummy', 1);
379 ( show <SELECT NAME="maxrecords" onChange="window.location = '<% $cgi->self_url %>;maxrecords=' + this.options[this.selectedIndex].value;">
381 % foreach my $max ( map { $_ * $confmax } qw( 1 5 10 25 ) ) {
382 <OPTION VALUE="<% $max %>" <% ( $maxrecords == $max ) ? 'SELECTED' : '' %>><% $max %></OPTION>
387 % $cgi->param('maxrecords', $maxrecords);
390 % if ( defined($opt{'html_posttotal'}) && $type ne 'html-print' ) {
391 <% ref($opt{'html_posttotal'})
392 ? &{$opt{'html_posttotal'}}()
393 : $opt{'html_posttotal'}
398 % if ( $opt{'count_addl'} ) {
400 % foreach my $count ( @{$opt{'count_addl'}} ) {
401 % my $data = $count_arrayref->[++$n];
402 % if ( ref($count) ) {
403 <% &{ $count }( $data ) %>
405 <% sprintf( $count, $data ) %><BR>
413 % unless ( $opt{'disable_download'} || $type eq 'html-print' ) {
417 Download full results<BR>
419 % $cgi->param('_type', "$xlsname.xls" );
420 as <A HREF="<% $cgi->self_url %>">Excel spreadsheet</A><BR>
422 % $cgi->param('_type', 'csv');
423 as <A HREF="<% $cgi->self_url %>">CSV file</A><BR>
425 % $cgi->param('_type', 'html-print');
426 as <A HREF="<% $cgi->self_url %>">printable copy</A>
428 <% $opt{'extra_choices_callback'}
429 ? &{$opt{'extra_choices_callback'}}($cgi->query_string)
434 % $cgi->param('_type', "html" );
442 % unless ( $type eq 'html_print' ) {
444 <% $pager = include( '/elements/pager.html',
446 'num_rows' => scalar(@$rows),
448 'maxrecords' => $maxrecords,
452 <% defined($opt{'html_form'})
453 ? ( ref($opt{'html_form'})
454 ? &{$opt{'html_form'}}()
462 <% include('/elements/table-grid.html') %>
466 % foreach my $header ( @{ $opt{header} } ) {
467 % my $label = ref($header) ? $header->{label} : $header;
470 % if ( $opt{header2} ) {
471 % if ( !length($opt{header2}->[$h2]) ) {
473 % splice @{ $opt{header2} }, $h2, 1;
476 % $style = 'STYLE="border-bottom: none"'
481 ROWSPAN = "<% $rowspan %>"
490 % if ( $opt{header2} ) {
492 % foreach my $header ( @{ $opt{header2} } ) {
493 % my $label = ref($header) ? $header->{label} : $header;
494 <TH CLASS="grid" BGCOLOR="#cccccc">
495 <FONT SIZE="-1"><% $label %></FONT>
501 % my $bgcolor1 = '#eeeeee';
502 % my $bgcolor2 = '#ffffff';
505 % foreach my $row ( @$rows ) {
507 % if ( $bgcolor eq $bgcolor1 ) {
508 % $bgcolor = $bgcolor2;
510 % $bgcolor = $bgcolor1;
515 % if ( $opt{'fields'} ) {
517 % my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
518 % my $onclicks = $opt{'link_onclicks'} ? [ @{$opt{'link_onclicks'}} ] : [];
519 % my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
520 % my $colors = $opt{'color'} ? [ @{$opt{'color'}} ] : [];
521 % my $sizes = $opt{'size'} ? [ @{$opt{'size'}} ] : [];
522 % my $styles = $opt{'style'} ? [ @{$opt{'style'}} ] : [];
523 % my $cstyles = $opt{'cell_style'} ? [ @{$opt{'cell_style'}} ] : [];
525 % foreach my $field (
528 % if ( ref($_) eq 'ARRAY' ) {
532 % '<TABLE CLASS="inv" CELLSPACING=0 CELLPADDING=0 WIDTH="100%">'.
546 % uc($_).'="'. $e->{$_}. '"';
548 % grep exists($e->{$_}),
549 % qw( align bgcolor colspan rowspan
550 % style valign width )
555 % ? '<A HREF="'. $e->{'link'}. '">'
559 % ? '<FONT SIZE="'.uc($e->{'size'}).'">'
562 % ( $e->{'data_style'}
563 % ? '<'. uc($e->{'data_style'}). '>'
567 % ( $e->{'data_style'}
568 % ? '</'. uc($e->{'data_style'}). '>'
571 % ( $e->{'size'} ? '</FONT>' : '' ).
572 % ( $e->{'link'} ? '</A>' : '' ).
588 % if ( ref($_) eq 'CODE' ) {
598 % my $class = ( $field =~ /^<TABLE/i ) ? 'inv' : 'grid';
600 % my $align = $aligns ? shift @$aligns : '';
601 % $align = " ALIGN=$align" if $align;
605 % my $link = shift @$links;
606 % my $onclick = shift @$onclicks;
608 % if ( ! $opt{'agent_virt'}
609 % || ( $null_link && ! $row->agentnum )
610 % || grep { $row->agentnum == $_ }
614 % $link = &{$link}($row)
615 % if ref($link) eq 'CODE';
617 % $onclick = &{$onclick}($row)
618 % if ref($onclick) eq 'CODE';
619 % $onclick = qq( onClick="$onclick") if $onclick;
622 % my( $url, $method ) = @{$link};
623 % if ( ref($method) eq 'CODE' ) {
624 % $a = $url. &{$method}($row);
626 % $a = $url. $row->$method();
628 % $a = qq(<A HREF="$a"$onclick>);
636 % my $color = shift @$colors;
637 % $color = &{$color}($row) if ref($color) eq 'CODE';
638 % my $size = shift @$sizes;
639 % $size = &{$size}($row) if ref($size) eq 'CODE';
640 % if ( $color || $size ) {
642 % ( $color ? "COLOR=#$color " : '' ).
643 % ( $size ? qq(SIZE="$size" ) : '' ).
647 % my($s, $es) = ( '', '' );
648 % my $style = shift @$styles;
649 % $style = &{$style}($row) if ref($style) eq 'CODE';
651 % $s = join( '', map "<$_>", split('', $style) );
652 % $es = join( '', map "</$_>", split('', $style) );
655 % my $cstyle = shift @$cstyles;
656 % $cstyle = &{$cstyle}($row) if ref($cstyle) eq 'CODE';
657 % $cstyle = qq(STYLE="$cstyle")
660 <TD CLASS="<% $class %>" BGCOLOR="<% $bgcolor %>" <% $align %> <% $cstyle %>><% $font %><% $a %><% $s %><% $field %><% $es %><% $a ? '</A>' : '' %><% $font ? '</FONT>' : '' %></TD>
666 % foreach ( @$row ) {
667 <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $_ %></TD>
676 % if ( $opt{'footer'} ) {
680 % foreach my $footer ( @{ $opt{'footer'} } ) {
681 <TD CLASS="grid" BGCOLOR="#dddddd" STYLE="border-top: dashed 1px black;"><i><% $footer %></i></TD>
696 % if ( $type eq 'html-print' ) {
702 <% defined($opt{'html_foot'})
703 ? ( ref($opt{'html_foot'})
704 ? &{$opt{'html_foot'}}()
710 <% include( '/elements/footer.html' ) %>
720 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
722 my $curuser = $FS::CurrentUser::CurrentUser;
731 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
732 unless !$opt{align} || ref($opt{align});
734 $opt{disable_download} = 0
735 if $opt{disable_download} && $curuser->access_right('Configuration download');
737 my @link_agentnums = ();
739 if ( $opt{'agent_virt'} ) {
741 @link_agentnums = $curuser->agentnums;
742 $null_link = $curuser->access_right( $opt{'agent_null_right_link'}
743 || $opt{'agent_null_right'} );
745 my $agentnums_sql = $curuser->agentnums_sql(
746 'null_right' => $opt{'agent_null_right'}
749 $opt{'query'}{'extra_sql'} .=
750 ( $opt{'query'}{'extra_sql'} =~ /WHERE/i || keys %{$opt{'query'}{'hashref'}}
752 : ' WHERE ' ). $agentnums_sql;
754 $opt{'count_query'} .=
755 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ). $agentnums_sql;
757 if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
758 and scalar($curuser->agentnums) > 1 ) {
759 #false laziness w/statuspos above
760 my $pos = $opt{'agent_pos'};
762 foreach my $att (qw( align style color size )) {
763 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
766 splice @{ $opt{'header'} }, $pos, 0, 'Agent';
767 splice @{ $opt{'align'} }, $pos, 0, 'c';
768 splice @{ $opt{'style'} }, $pos, 0, '';
769 splice @{ $opt{'size'} }, $pos, 0, '';
770 splice @{ $opt{'fields'} }, $pos, 0,
771 sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
772 splice @{ $opt{'color'} }, $pos, 0, '';
773 splice @{ $opt{'links'} }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
775 splice @{ $opt{'link_onclicks'} }, $pos, 0, ''
776 if $opt{'link_onclicks'};
782 if ( $opt{'disableable'} ) {
784 unless ( $cgi->param('showdisabled') ) { #modify searches
786 $opt{'query'}{'hashref'}{'disabled'} = '';
787 $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
789 $opt{'count_query'} .=
790 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
791 "( disabled = '' OR disabled IS NULL )";
793 } elsif ( $opt{'disabled_statuspos'}
794 || $opt{'disabled_statuspos'} eq '0' ) { #add status column
796 my $pos = $opt{'disabled_statuspos'};
798 foreach my $att (qw( align style color size )) {
799 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
802 splice @{ $opt{'header'} }, $pos, 0, 'Status';
803 splice @{ $opt{'align'} }, $pos, 0, 'c';
804 splice @{ $opt{'style'} }, $pos, 0, 'b';
805 splice @{ $opt{'size'} }, $pos, 0, '';
806 splice @{ $opt{'fields'} }, $pos, 0,
807 sub { shift->disabled ? 'DISABLED' : 'Active'; };
808 splice @{ $opt{'color'} }, $pos, 0,
809 sub { shift->disabled ? 'FF0000' : '00CC00'; };
810 splice @{ $opt{'links'} }, $pos, 0, ''
812 splice @{ $opt{'link_onlicks'} }, $pos, 0, ''
813 if $opt{'link_onlicks'};
816 #add show/hide disabled links
817 my $items = $opt{'name'} || PL($opt{'name_singular'});
818 if ( $cgi->param('showdisabled') ) {
819 $cgi->param('showdisabled', 0);
820 $opt{'html_posttotal'} .=
821 '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!;
822 $cgi->param('showdisabled', 1);
824 $cgi->param('showdisabled', 1);
825 $opt{'html_posttotal'} .=
826 '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!;
827 $cgi->param('showdisabled', 0);
832 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|select|html(-print)?)$/
836 my($confmax, $maxrecords, $total, $offset, $count_arrayref);
838 unless ( $type =~ /^(csv|\w*\.xls)$/ ) {
840 unless (exists($opt{count_query}) && length($opt{count_query})) {
841 ( $opt{count_query} = $opt{query} ) =~
842 s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
845 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
847 ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
848 "( disabled = '' OR disabled IS NULL )";
851 unless ( $type eq 'html-print' ) {
853 #setup some pagination things if we're in html mode
855 my $conf = new FS::Conf;
856 $confmax = $conf->config('maxsearchrecordsperpage');
857 if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
860 $maxrecords ||= $confmax;
863 $limit = $maxrecords ? "LIMIT $maxrecords" : '';
865 $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
866 $limit .= " OFFSET $offset" if $offset;
870 my $count_sth = dbh->prepare($opt{'count_query'})
871 or die "Error preparing $opt{'count_query'}: ". dbh->errstr;
873 or die "Error executing $opt{'count_query'}: ". $count_sth->errstr;
874 $count_arrayref = $count_sth->fetchrow_arrayref;
875 $total = $count_arrayref->[0];
881 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
883 if ( ref($opt{query}) ) {
885 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
886 #%search = ( 'disabled' => '' );
887 $opt{'query'}->{'hashref'}->{'disabled'} = '';
888 $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
891 #eval "use FS::$opt{'query'};";
893 'select' => $opt{'query'}->{'select'},
894 'table' => $opt{'query'}->{'table'},
895 'addl_from' => (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : ''),
896 'hashref' => $opt{'query'}->{'hashref'} || {},
897 'extra_sql' => $opt{'query'}->{'extra_sql'},
898 'order_by' => $opt{'query'}->{'order_by'}. " $limit",
901 my $sth = dbh->prepare("$opt{'query'} $limit")
902 or die "Error preparing $opt{'query'}: ". dbh->errstr;
904 or die "Error executing $opt{'query'}: ". $sth->errstr;
906 #can get # of rows without fetching them all?
907 $rows = $sth->fetchall_arrayref;
909 $header ||= $sth->{NAME};