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
69 # some HTML callbacks...
70 'menubar' => '', #menubar arrayref
71 'html_init' => '', #after the header/menubar and before the pager
72 'html_form' => '', #after the pager, right before the results
73 # (only shown if there are results)
74 # (use this for any form-opening tag rather than
75 # html_init, to avoid a nested form)
76 'html_foot' => '', #at the bottom
77 'html_posttotal' => '', #at the bottom
78 # (these three can be strings or coderefs)
80 'count_addl' => [], #additional count fields listref of sprintf strings or coderefs
81 # [ $money_char.'%.2f total paid', ],
83 #second (smaller) header line, currently only for HTML
86 { 'label' => 'Another Item',
91 #listref of column footers
95 'disable_download' => '', # set true to hide the CSV/Excel download links
96 'disable_nonefound' => '', # set true to disable the "No matching Xs found"
99 #handling "disabled" fields in the records
100 'disableable' => 1, # set set to 1 (or column position for "disabled"
101 # status col) to enable if this table has a "disabled"
102 # field, to hide disabled records & have
103 # "show disabled/hide disabled" links
104 #(can't be used with a literal query)
105 'disabled_statuspos' => 3, #optional position (starting from 0) to insert
106 #a Status column when showing disabled records
107 #(query needs to be a qsearch hashref and
108 # header & fields need to be defined)
110 #handling agent virtualization
111 'agent_virt' => 1, # set true if this search should be agent-virtualized
112 'agent_null_right' => 'Access Right', #opt. right to view global records
113 'agent_pos' => 3, #optional position (starting from 0) to insert
115 #(query needs to be a qsearch hashref and
116 # header & fields need to be defined)
118 # link & display properties for fields
120 #listref - each item is the empty string,
121 # or a listref of link and method name to append,
122 # or a listref of link and coderef to run and append
123 # or a coderef that returns such a listref
126 #listref - each item is the empty string,
127 # or a string onClick handler for the corresponding link
128 # or a coderef that returns string onClick handler
129 'link_onclicks' => [],
131 #one letter for each column, left/right/center/none
132 # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
135 #listrefs of ( scalars or coderefs )
136 #currently only HTML, maybe eventually Excel too
139 'style' => [], #<B> or <I>, etc.
140 'cell_style' => [], #STYLE= attribute of TR, very HTML-specific...
145 % if ( $type eq 'csv' ) {
147 % #http_header('Content-Type' => 'text/comma-separated-values' ); #IE chokes
148 % http_header('Content-Type' => 'text/plain' );
150 % my $csv = new Text::CSV_XS { 'always_quote' => 1,
151 % 'eol' => "\n", #"\015\012", #"\012"
154 % $csv->combine(@$header); #or die $csv->status;
159 % foreach my $row ( @$rows ) {
161 % if ( $opt{'fields'} ) {
165 % foreach my $field ( @{$opt{'fields'}} ) {
166 % if ( ref($field) eq 'CODE' ) {
169 % ? '(N/A)' #unimplemented
174 % push @line, $row->$field();
178 % $csv->combine(@line); #or die $csv->status;
181 % $csv->combine(@$row); #or die $csv->status;
190 % #} elsif ( $type eq 'excel' ) {
191 % } elsif ( $type =~ /\.xls$/ ) {
193 % #http_header('Content-Type' => 'application/excel' ); #eww
194 % #http_header('Content-Type' => 'application/msexcel' ); #alas
195 % #http_header('Content-Type' => 'application/x-msexcel' ); #?
197 % #http://support.microsoft.com/kb/199841
198 % http_header('Content-Type' => 'application/vnd.ms-excel' );
200 % #http://support.microsoft.com/kb/812935
201 % #http://support.microsoft.com/kb/323308
202 % $HTML::Mason::Commands::r->headers_out->{'Cache-control'} = 'max-age=0';
205 % my $XLS = new IO::Scalar \$data;
206 % my $workbook = Spreadsheet::WriteExcel->new($XLS)
207 % or die "Error opening .xls file: $!";
209 % my $worksheet = $workbook->add_worksheet(substr($opt{'title'},0,31));
213 % $worksheet->write($r, $c++, $_) foreach @$header;
215 % foreach my $row ( @$rows ) {
219 % if ( $opt{'fields'} ) {
221 % #my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
222 % #my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
224 % foreach my $field ( @{$opt{'fields'}} ) {
225 % #my $align = $aligns ? shift @$aligns : '';
226 % #$align = " ALIGN=$align" if $align;
229 % # my $link = shift @$links;
230 % # $link = &{$link}($row) if ref($link) eq 'CODE';
232 % # my( $url, $method ) = @{$link};
233 % # if ( ref($method) eq 'CODE' ) {
234 % # $a = $url. &{$method}($row);
236 % # $a = $url. $row->$method();
238 % # $a = qq(<A HREF="$a">);
241 % if ( ref($field) eq 'CODE' ) {
242 % foreach my $value ( &{$field}($row) ) {
243 % if ( ref($value) eq 'ARRAY' ) {
244 % $worksheet->write($r, $c++, '(N/A)' ); #unimplemented
246 % $worksheet->write($r, $c++, $value );
250 % $worksheet->write($r, $c++, $row->$field() );
255 % $worksheet->write($r, $c++, $_) foreach @$row;
260 % $workbook->close();# or die "Error creating .xls file: $!";
262 % http_header('Content-Length' => length($data) );
267 % } else { # regular HTML
269 % if ( exists($opt{'redirect'}) && scalar(@$rows) == 1 && $total == 1
270 % && $type ne 'html-print'
272 % my $redirect = $opt{'redirect'};
273 % $redirect = &{$redirect}($rows->[0]) if ref($redirect) eq 'CODE';
274 % my( $url, $method ) = @$redirect;
275 % redirect( $url. $rows->[0]->$method() );
277 % if ( $opt{'name_singular'} ) {
278 % $opt{'name'} = PL($opt{'name_singular'});
280 % ( my $xlsname = $opt{'name'} ) =~ s/\W//g;
281 % if ( $total == 1 ) {
282 % if ( $opt{'name_singular'} ) {
283 % $opt{'name'} = $opt{'name_singular'}
285 % #$opt{'name'} =~ s/s$// if $total == 1;
286 % $opt{'name'} =~ s/((s)e)?s$/$2/ if $total == 1;
290 % if ( $type eq 'html-print' ) {
292 <% include( '/elements/header-popup.html', $opt{'title'} ) %>
297 % if ( $opt{'menubar'} ) {
298 % @menubar = @{ $opt{'menubar'} };
300 % # @menubar = ( 'Main menu' => $p );
303 <% include( '/elements/header.html', $opt{'title'},
304 include( '/elements/menubar.html', @menubar )
308 <% defined($opt{'html_init'})
309 ? ( ref($opt{'html_init'})
310 ? &{$opt{'html_init'}}()
318 % unless ( $total ) {
319 % unless ( $opt{'disable_nonefound'} ) {
320 No matching <% $opt{'name'} %> found.<BR>
324 % if ( $total || $opt{'disableable'} ) { #hmm... and there *are* ones to show??
333 <% $total %> total <% $opt{'name'} %>
335 % if ( $confmax && $total > $confmax && $type ne 'html-print' ) {
336 % $cgi->delete('maxrecords');
337 % $cgi->param('_dummy', 1);
339 %# ( show <SELECT NAME="maxrecords" onChange="this.form.submit();">
340 ( show <SELECT NAME="maxrecords" onChange="window.location = '<% $cgi->self_url %>;maxrecords=' + this.options[this.selectedIndex].value;">
342 % foreach my $max ( map { $_ * $confmax } qw( 1 5 10 25 ) ) {
343 <OPTION VALUE="<% $max %>" <% ( $maxrecords == $max ) ? 'SELECTED' : '' %>><% $max %></OPTION>
348 % $cgi->param('maxrecords', $maxrecords);
351 % if ( defined($opt{'html_posttotal'}) && $type ne 'html-print' ) {
352 <% ref($opt{'html_posttotal'})
353 ? &{$opt{'html_posttotal'}}()
354 : $opt{'html_posttotal'}
359 % if ( $opt{'count_addl'} ) {
361 % foreach my $count ( @{$opt{'count_addl'}} ) {
362 % my $data = $count_arrayref->[++$n];
363 % if ( ref($count) ) {
364 <% &{ $count }( $data ) %>
366 <% sprintf( $count, $data ) %><BR>
374 % unless ( $opt{'disable_download'} || $type eq 'html-print' ) {
378 Download full results<BR>
380 % $cgi->param('_type', "$xlsname.xls" );
381 as <A HREF="<% $cgi->self_url %>">Excel spreadsheet</A><BR>
383 % $cgi->param('_type', 'csv');
384 as <A HREF="<% $cgi->self_url %>">CSV file</A><BR>
386 % $cgi->param('_type', 'html-print');
387 as <A HREF="<% $cgi->self_url %>">printable copy</A>
389 <% $opt{'extra_choices_callback'}
390 ? &{$opt{'extra_choices_callback'}}($cgi->query_string)
395 % $cgi->param('_type', "html" );
403 % unless ( $type eq 'html_print' ) {
405 <% $pager = include( '/elements/pager.html',
407 'num_rows' => scalar(@$rows),
409 'maxrecords' => $maxrecords,
413 <% defined($opt{'html_form'})
414 ? ( ref($opt{'html_form'})
415 ? &{$opt{'html_form'}}()
423 <% include('/elements/table-grid.html') %>
427 % foreach my $header ( @{ $opt{header} } ) {
428 % my $label = ref($header) ? $header->{label} : $header;
431 % if ( $opt{header2} ) {
432 % if ( !length($opt{header2}->[$h2]) ) {
434 % splice @{ $opt{header2} }, $h2, 1;
437 % $style = 'STYLE="border-bottom: none"'
442 ROWSPAN = "<% $rowspan %>"
451 % if ( $opt{header2} ) {
453 % foreach my $header ( @{ $opt{header2} } ) {
454 % my $label = ref($header) ? $header->{label} : $header;
455 <TH CLASS="grid" BGCOLOR="#cccccc">
456 <FONT SIZE="-1"><% $label %></FONT>
462 % my $bgcolor1 = '#eeeeee';
463 % my $bgcolor2 = '#ffffff';
466 % foreach my $row ( @$rows ) {
468 % if ( $bgcolor eq $bgcolor1 ) {
469 % $bgcolor = $bgcolor2;
471 % $bgcolor = $bgcolor1;
476 % if ( $opt{'fields'} ) {
478 % my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
479 % my $onclicks = $opt{'link_onclicks'} ? [ @{$opt{'link_onclicks'}} ] : [];
480 % my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
481 % my $colors = $opt{'color'} ? [ @{$opt{'color'}} ] : [];
482 % my $sizes = $opt{'size'} ? [ @{$opt{'size'}} ] : [];
483 % my $styles = $opt{'style'} ? [ @{$opt{'style'}} ] : [];
484 % my $cstyles = $opt{'cell_style'} ? [ @{$opt{'cell_style'}} ] : [];
486 % foreach my $field (
489 % if ( ref($_) eq 'ARRAY' ) {
493 % '<TABLE CLASS="inv" CELLSPACING=0 CELLPADDING=0 WIDTH="100%">'.
507 % uc($_).'="'. $e->{$_}. '"';
509 % grep exists($e->{$_}),
510 % qw( align bgcolor colspan rowspan
511 % style valign width )
516 % ? '<A HREF="'. $e->{'link'}. '">'
520 % ? '<FONT SIZE="'.uc($e->{'size'}).'">'
523 % ( $e->{'data_style'}
524 % ? '<'. uc($e->{'data_style'}). '>'
528 % ( $e->{'data_style'}
529 % ? '</'. uc($e->{'data_style'}). '>'
532 % ( $e->{'size'} ? '</FONT>' : '' ).
533 % ( $e->{'link'} ? '</A>' : '' ).
549 % if ( ref($_) eq 'CODE' ) {
559 % my $class = ( $field =~ /^<TABLE/i ) ? 'inv' : 'grid';
561 % my $align = $aligns ? shift @$aligns : '';
562 % $align = " ALIGN=$align" if $align;
566 % my $link = shift @$links;
567 % $link = &{$link}($row)
568 % if ref($link) eq 'CODE';
570 % my $onclick = shift @$onclicks;
571 % $onclick = &{$onclick}($row)
572 % if ref($onclick) eq 'CODE';
573 % $onclick = qq( onClick="$onclick") if $onclick;
576 % my( $url, $method ) = @{$link};
577 % if ( ref($method) eq 'CODE' ) {
578 % $a = $url. &{$method}($row);
580 % $a = $url. $row->$method();
582 % $a = qq(<A HREF="$a"$onclick>);
587 % my $color = shift @$colors;
588 % $color = &{$color}($row) if ref($color) eq 'CODE';
589 % my $size = shift @$sizes;
590 % $size = &{$size}($row) if ref($size) eq 'CODE';
591 % if ( $color || $size ) {
593 % ( $color ? "COLOR=#$color " : '' ).
594 % ( $size ? qq(SIZE="$size" ) : '' ).
598 % my($s, $es) = ( '', '' );
599 % my $style = shift @$styles;
600 % $style = &{$style}($row) if ref($style) eq 'CODE';
602 % $s = join( '', map "<$_>", split('', $style) );
603 % $es = join( '', map "</$_>", split('', $style) );
606 % my $cstyle = shift @$cstyles;
607 % $cstyle = &{$cstyle}($row) if ref($cstyle) eq 'CODE';
608 % $cstyle = qq(STYLE="$cstyle")
611 <TD CLASS="<% $class %>" BGCOLOR="<% $bgcolor %>" <% $align %> <% $cstyle %>><% $font %><% $a %><% $s %><% $field %><% $es %><% $a ? '</A>' : '' %><% $font ? '</FONT>' : '' %></TD>
617 % foreach ( @$row ) {
618 <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $_ %></TD>
627 % if ( $opt{'footer'} ) {
631 % foreach my $footer ( @{ $opt{'footer'} } ) {
632 <TD CLASS="grid" BGCOLOR="#dddddd" STYLE="border-top: dashed 1px black;"><i><% $footer %></i></TD>
647 % if ( $type eq 'html-print' ) {
653 <% defined($opt{'html_foot'})
654 ? ( ref($opt{'html_foot'})
655 ? &{$opt{'html_foot'}}()
661 <% include( '/elements/footer.html' ) %>
671 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
673 my $curuser = $FS::CurrentUser::CurrentUser;
682 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
683 unless !$opt{align} || ref($opt{align});
685 if ( $opt{'agent_virt'} ) {
687 my $agentnums_sql = $curuser->agentnums_sql(
688 'null_right' => $opt{'agent_null_right'}
691 $opt{'query'}{'extra_sql'} .=
692 ( $opt{'query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
694 $opt{'count_query'} .=
695 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
698 if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
699 and scalar($curuser->agentnums) > 1 ) {
700 #false laziness w/statuspos above
701 my $pos = $opt{'agent_pos'};
703 foreach my $att (qw( align style color size )) {
704 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
707 splice @{ $opt{'header'} }, $pos, 0, 'Agent';
708 splice @{ $opt{'align'} }, $pos, 0, 'c';
709 splice @{ $opt{'style'} }, $pos, 0, '';
710 splice @{ $opt{'size'} }, $pos, 0, '';
711 splice @{ $opt{'fields'} }, $pos, 0,
712 sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
713 splice @{ $opt{'color'} }, $pos, 0, '';
714 splice @{ $opt{'links'} }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
716 splice @{ $opt{'link_onclicks'} }, $pos, 0, ''
717 if $opt{'link_onclicks'};
723 if ( $opt{'disableable'} ) {
725 unless ( $cgi->param('showdisabled') ) { #modify searches
727 $opt{'query'}{'hashref'}{'disabled'} = '';
728 $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
730 $opt{'count_query'} .=
731 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
732 "( disabled = '' OR disabled IS NULL )";
734 } elsif ( $opt{'disabled_statuspos'}
735 || $opt{'disabled_statuspos'} eq '0' ) { #add status column
737 my $pos = $opt{'disabled_statuspos'};
739 foreach my $att (qw( align style color size )) {
740 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
743 splice @{ $opt{'header'} }, $pos, 0, 'Status';
744 splice @{ $opt{'align'} }, $pos, 0, 'c';
745 splice @{ $opt{'style'} }, $pos, 0, 'b';
746 splice @{ $opt{'size'} }, $pos, 0, '';
747 splice @{ $opt{'fields'} }, $pos, 0,
748 sub { shift->disabled ? 'DISABLED' : 'Active'; };
749 splice @{ $opt{'color'} }, $pos, 0,
750 sub { shift->disabled ? 'FF0000' : '00CC00'; };
751 splice @{ $opt{'links'} }, $pos, 0, ''
753 splice @{ $opt{'link_onlicks'} }, $pos, 0, ''
754 if $opt{'link_onlicks'};
757 #add show/hide disabled links
758 my $items = $opt{'name'} || PL($opt{'name_singular'});
759 if ( $cgi->param('showdisabled') ) {
760 $cgi->param('showdisabled', 0);
761 $opt{'html_posttotal'} .=
762 '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!;
763 $cgi->param('showdisabled', 1);
765 $cgi->param('showdisabled', 1);
766 $opt{'html_posttotal'} .=
767 '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!;
768 $cgi->param('showdisabled', 0);
773 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|html(-print)?)$/
777 my($confmax, $maxrecords, $total, $offset, $count_arrayref);
779 unless ( $type =~ /^(csv|\w*\.xls)$/ ) {
781 unless (exists($opt{count_query}) && length($opt{count_query})) {
782 ( $opt{count_query} = $opt{query} ) =~
783 s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
786 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
788 ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
789 "( disabled = '' OR disabled IS NULL )";
792 unless ( $type eq 'html-print' ) {
794 #setup some pagination things if we're in html mode
796 my $conf = new FS::Conf;
797 $confmax = $conf->config('maxsearchrecordsperpage');
798 if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
801 $maxrecords ||= $confmax;
804 $limit = $maxrecords ? "LIMIT $maxrecords" : '';
806 $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
807 $limit .= " OFFSET $offset" if $offset;
811 my $count_sth = dbh->prepare($opt{'count_query'})
812 or die "Error preparing $opt{'count_query'}: ". dbh->errstr;
814 or die "Error executing $opt{'count_query'}: ". $count_sth->errstr;
815 $count_arrayref = $count_sth->fetchrow_arrayref;
816 $total = $count_arrayref->[0];
822 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
824 if ( ref($opt{query}) ) {
826 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
827 #%search = ( 'disabled' => '' );
828 $opt{'query'}->{'hashref'}->{'disabled'} = '';
829 $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
832 #eval "use FS::$opt{'query'};";
834 'select' => $opt{'query'}->{'select'},
835 'table' => $opt{'query'}->{'table'},
836 'addl_from' => (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : ''),
837 'hashref' => $opt{'query'}->{'hashref'} || {},
838 'extra_sql' => $opt{'query'}->{'extra_sql'},
839 'order_by' => $opt{'query'}->{'order_by'}. " $limit",
842 my $sth = dbh->prepare("$opt{'query'} $limit")
843 or die "Error preparing $opt{'query'}: ". dbh->errstr;
845 or die "Error executing $opt{'query'}: ". $sth->errstr;
847 #can get # of rows without fetching them all?
848 $rows = $sth->fetchall_arrayref;
850 $header ||= $sth->{NAME};