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_total' => '', # set true to hide the total"
97 'disable_maxselect' => '', # set true to disable record/page selection
98 'disable_nonefound' => '', # set true to disable the "No matching Xs found"
101 #handling "disabled" fields in the records
102 'disableable' => 1, # set set to 1 (or column position for "disabled"
103 # status col) to enable if this table has a "disabled"
104 # field, to hide disabled records & have
105 # "show disabled/hide disabled" links
106 #(can't be used with a literal query)
107 'disabled_statuspos' => 3, #optional position (starting from 0) to insert
108 #a Status column when showing disabled records
109 #(query needs to be a qsearch hashref and
110 # header & fields need to be defined)
112 #handling agent virtualization
113 'agent_virt' => 1, # set true if this search should be agent-virtualized
114 'agent_null_right' => 'Access Right', #opt. right to view global records
115 'agent_pos' => 3, #optional position (starting from 0) to insert
117 #(query needs to be a qsearch hashref and
118 # header & fields need to be defined)
120 # link & display properties for fields
122 #listref - each item is the empty string,
123 # or a listref of link and method name to append,
124 # or a listref of link and coderef to run and append
125 # or a coderef that returns such a listref
128 #listref - each item is the empty string,
129 # or a string onClick handler for the corresponding link
130 # or a coderef that returns string onClick handler
131 'link_onclicks' => [],
133 #one letter for each column, left/right/center/none
134 # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
137 #listrefs of ( scalars or coderefs )
138 #currently only HTML, maybe eventually Excel too
141 'style' => [], #<B> or <I>, etc.
142 'cell_style' => [], #STYLE= attribute of TR, very HTML-specific...
147 % if ( $type eq 'csv' ) {
149 % #http_header('Content-Type' => 'text/comma-separated-values' ); #IE chokes
150 % http_header('Content-Type' => 'text/plain' );
152 % my $csv = new Text::CSV_XS { 'always_quote' => 1,
153 % 'eol' => "\n", #"\015\012", #"\012"
156 % $csv->combine(@$header); #or die $csv->status;
161 % foreach my $row ( @$rows ) {
163 % if ( $opt{'fields'} ) {
167 % foreach my $field ( @{$opt{'fields'}} ) {
168 % if ( ref($field) eq 'CODE' ) {
171 % ? '(N/A)' #unimplemented
176 % push @line, $row->$field();
180 % $csv->combine(@line); #or die $csv->status;
183 % $csv->combine(@$row); #or die $csv->status;
192 % #} elsif ( $type eq 'excel' ) {
193 % } elsif ( $type =~ /\.xls$/ ) {
195 % #http_header('Content-Type' => 'application/excel' ); #eww
196 % #http_header('Content-Type' => 'application/msexcel' ); #alas
197 % #http_header('Content-Type' => 'application/x-msexcel' ); #?
199 % #http://support.microsoft.com/kb/199841
200 % http_header('Content-Type' => 'application/vnd.ms-excel' );
202 % #http://support.microsoft.com/kb/812935
203 % #http://support.microsoft.com/kb/323308
204 % $HTML::Mason::Commands::r->headers_out->{'Cache-control'} = 'max-age=0';
207 % my $XLS = new IO::Scalar \$data;
208 % my $workbook = Spreadsheet::WriteExcel->new($XLS)
209 % or die "Error opening .xls file: $!";
211 % my $worksheet = $workbook->add_worksheet(substr($opt{'title'},0,31));
215 % $worksheet->write($r, $c++, $_) foreach @$header;
217 % foreach my $row ( @$rows ) {
221 % if ( $opt{'fields'} ) {
223 % #my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
224 % #my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
226 % foreach my $field ( @{$opt{'fields'}} ) {
227 % #my $align = $aligns ? shift @$aligns : '';
228 % #$align = " ALIGN=$align" if $align;
231 % # my $link = shift @$links;
232 % # $link = &{$link}($row) if ref($link) eq 'CODE';
234 % # my( $url, $method ) = @{$link};
235 % # if ( ref($method) eq 'CODE' ) {
236 % # $a = $url. &{$method}($row);
238 % # $a = $url. $row->$method();
240 % # $a = qq(<A HREF="$a">);
243 % if ( ref($field) eq 'CODE' ) {
244 % foreach my $value ( &{$field}($row) ) {
245 % if ( ref($value) eq 'ARRAY' ) {
246 % $worksheet->write($r, $c++, '(N/A)' ); #unimplemented
248 % $worksheet->write($r, $c++, $value );
252 % $worksheet->write($r, $c++, $row->$field() );
257 % $worksheet->write($r, $c++, $_) foreach @$row;
262 % $workbook->close();# or die "Error creating .xls file: $!";
264 % http_header('Content-Length' => length($data) );
269 % } else { # regular HTML
271 % if ( exists($opt{'redirect'}) && scalar(@$rows) == 1 && $total == 1
272 % && $type ne 'html-print'
274 % my $redirect = $opt{'redirect'};
275 % $redirect = &{$redirect}($rows->[0]) if ref($redirect) eq 'CODE';
276 % my( $url, $method ) = @$redirect;
277 % redirect( $url. $rows->[0]->$method() );
279 % if ( $opt{'name_singular'} ) {
280 % $opt{'name'} = PL($opt{'name_singular'});
282 % ( my $xlsname = $opt{'name'} ) =~ s/\W//g;
283 % if ( $total == 1 ) {
284 % if ( $opt{'name_singular'} ) {
285 % $opt{'name'} = $opt{'name_singular'}
287 % #$opt{'name'} =~ s/s$// if $total == 1;
288 % $opt{'name'} =~ s/((s)e)?s$/$2/ if $total == 1;
292 % if ( $type eq 'html-print' ) {
294 <% include( '/elements/header-popup.html', $opt{'title'} ) %>
296 % } elsif ( $type eq 'select' ) {
298 <% include( '/elements/header-popup.html', $opt{'title'} ) %>
299 <% defined($opt{'html_init'})
300 ? ( ref($opt{'html_init'})
301 ? &{$opt{'html_init'}}()
310 % if ( $opt{'menubar'} ) {
311 % @menubar = @{ $opt{'menubar'} };
313 % # @menubar = ( 'Main menu' => $p );
316 <% include( '/elements/header.html', $opt{'title'},
317 include( '/elements/menubar.html', @menubar )
321 <% defined($opt{'html_init'})
322 ? ( ref($opt{'html_init'})
323 ? &{$opt{'html_init'}}()
331 % unless ( $total ) {
332 % unless ( $opt{'disable_nonefound'} ) {
333 No matching <% $opt{'name'} %> found.<BR>
337 % if ( $total || $opt{'disableable'} ) { #hmm... and there *are* ones to show??
346 % if (! $opt{'disable_total'}) {
347 <% $total %> total <% $opt{'name'} %>
350 % if ( $confmax && $total > $confmax
351 % && ! $opt{'disable_maxselect'}
352 % && $type ne 'html-print' )
354 % $cgi->delete('maxrecords');
355 % $cgi->param('_dummy', 1);
357 ( show <SELECT NAME="maxrecords" onChange="window.location = '<% $cgi->self_url %>;maxrecords=' + this.options[this.selectedIndex].value;">
359 % foreach my $max ( map { $_ * $confmax } qw( 1 5 10 25 ) ) {
360 <OPTION VALUE="<% $max %>" <% ( $maxrecords == $max ) ? 'SELECTED' : '' %>><% $max %></OPTION>
365 % $cgi->param('maxrecords', $maxrecords);
368 % if ( defined($opt{'html_posttotal'}) && $type ne 'html-print' ) {
369 <% ref($opt{'html_posttotal'})
370 ? &{$opt{'html_posttotal'}}()
371 : $opt{'html_posttotal'}
376 % if ( $opt{'count_addl'} ) {
378 % foreach my $count ( @{$opt{'count_addl'}} ) {
379 % my $data = $count_arrayref->[++$n];
380 % if ( ref($count) ) {
381 <% &{ $count }( $data ) %>
383 <% sprintf( $count, $data ) %><BR>
391 % unless ( $opt{'disable_download'} || $type eq 'html-print' ) {
395 Download full results<BR>
397 % $cgi->param('_type', "$xlsname.xls" );
398 as <A HREF="<% $cgi->self_url %>">Excel spreadsheet</A><BR>
400 % $cgi->param('_type', 'csv');
401 as <A HREF="<% $cgi->self_url %>">CSV file</A><BR>
403 % $cgi->param('_type', 'html-print');
404 as <A HREF="<% $cgi->self_url %>">printable copy</A>
406 <% $opt{'extra_choices_callback'}
407 ? &{$opt{'extra_choices_callback'}}($cgi->query_string)
412 % $cgi->param('_type', "html" );
420 % unless ( $type eq 'html_print' ) {
422 <% $pager = include( '/elements/pager.html',
424 'num_rows' => scalar(@$rows),
426 'maxrecords' => $maxrecords,
430 <% defined($opt{'html_form'})
431 ? ( ref($opt{'html_form'})
432 ? &{$opt{'html_form'}}()
440 <% include('/elements/table-grid.html') %>
444 % foreach my $header ( @{ $opt{header} } ) {
445 % my $label = ref($header) ? $header->{label} : $header;
448 % if ( $opt{header2} ) {
449 % if ( !length($opt{header2}->[$h2]) ) {
451 % splice @{ $opt{header2} }, $h2, 1;
454 % $style = 'STYLE="border-bottom: none"'
459 ROWSPAN = "<% $rowspan %>"
468 % if ( $opt{header2} ) {
470 % foreach my $header ( @{ $opt{header2} } ) {
471 % my $label = ref($header) ? $header->{label} : $header;
472 <TH CLASS="grid" BGCOLOR="#cccccc">
473 <FONT SIZE="-1"><% $label %></FONT>
479 % my $bgcolor1 = '#eeeeee';
480 % my $bgcolor2 = '#ffffff';
483 % foreach my $row ( @$rows ) {
485 % if ( $bgcolor eq $bgcolor1 ) {
486 % $bgcolor = $bgcolor2;
488 % $bgcolor = $bgcolor1;
493 % if ( $opt{'fields'} ) {
495 % my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
496 % my $onclicks = $opt{'link_onclicks'} ? [ @{$opt{'link_onclicks'}} ] : [];
497 % my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
498 % my $colors = $opt{'color'} ? [ @{$opt{'color'}} ] : [];
499 % my $sizes = $opt{'size'} ? [ @{$opt{'size'}} ] : [];
500 % my $styles = $opt{'style'} ? [ @{$opt{'style'}} ] : [];
501 % my $cstyles = $opt{'cell_style'} ? [ @{$opt{'cell_style'}} ] : [];
503 % foreach my $field (
506 % if ( ref($_) eq 'ARRAY' ) {
510 % '<TABLE CLASS="inv" CELLSPACING=0 CELLPADDING=0 WIDTH="100%">'.
524 % uc($_).'="'. $e->{$_}. '"';
526 % grep exists($e->{$_}),
527 % qw( align bgcolor colspan rowspan
528 % style valign width )
533 % ? '<A HREF="'. $e->{'link'}. '">'
537 % ? '<FONT SIZE="'.uc($e->{'size'}).'">'
540 % ( $e->{'data_style'}
541 % ? '<'. uc($e->{'data_style'}). '>'
545 % ( $e->{'data_style'}
546 % ? '</'. uc($e->{'data_style'}). '>'
549 % ( $e->{'size'} ? '</FONT>' : '' ).
550 % ( $e->{'link'} ? '</A>' : '' ).
566 % if ( ref($_) eq 'CODE' ) {
576 % my $class = ( $field =~ /^<TABLE/i ) ? 'inv' : 'grid';
578 % my $align = $aligns ? shift @$aligns : '';
579 % $align = " ALIGN=$align" if $align;
583 % my $link = shift @$links;
584 % $link = &{$link}($row)
585 % if ref($link) eq 'CODE';
587 % my $onclick = shift @$onclicks;
588 % $onclick = &{$onclick}($row)
589 % if ref($onclick) eq 'CODE';
590 % $onclick = qq( onClick="$onclick") if $onclick;
593 % my( $url, $method ) = @{$link};
594 % if ( ref($method) eq 'CODE' ) {
595 % $a = $url. &{$method}($row);
597 % $a = $url. $row->$method();
599 % $a = qq(<A HREF="$a"$onclick>);
604 % my $color = shift @$colors;
605 % $color = &{$color}($row) if ref($color) eq 'CODE';
606 % my $size = shift @$sizes;
607 % $size = &{$size}($row) if ref($size) eq 'CODE';
608 % if ( $color || $size ) {
610 % ( $color ? "COLOR=#$color " : '' ).
611 % ( $size ? qq(SIZE="$size" ) : '' ).
615 % my($s, $es) = ( '', '' );
616 % my $style = shift @$styles;
617 % $style = &{$style}($row) if ref($style) eq 'CODE';
619 % $s = join( '', map "<$_>", split('', $style) );
620 % $es = join( '', map "</$_>", split('', $style) );
623 % my $cstyle = shift @$cstyles;
624 % $cstyle = &{$cstyle}($row) if ref($cstyle) eq 'CODE';
625 % $cstyle = qq(STYLE="$cstyle")
628 <TD CLASS="<% $class %>" BGCOLOR="<% $bgcolor %>" <% $align %> <% $cstyle %>><% $font %><% $a %><% $s %><% $field %><% $es %><% $a ? '</A>' : '' %><% $font ? '</FONT>' : '' %></TD>
634 % foreach ( @$row ) {
635 <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $_ %></TD>
644 % if ( $opt{'footer'} ) {
648 % foreach my $footer ( @{ $opt{'footer'} } ) {
649 <TD CLASS="grid" BGCOLOR="#dddddd" STYLE="border-top: dashed 1px black;"><i><% $footer %></i></TD>
664 % if ( $type eq 'html-print' ) {
670 <% defined($opt{'html_foot'})
671 ? ( ref($opt{'html_foot'})
672 ? &{$opt{'html_foot'}}()
678 <% include( '/elements/footer.html' ) %>
688 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
690 my $curuser = $FS::CurrentUser::CurrentUser;
699 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
700 unless !$opt{align} || ref($opt{align});
702 if ( $opt{'agent_virt'} ) {
704 my $agentnums_sql = $curuser->agentnums_sql(
705 'null_right' => $opt{'agent_null_right'}
708 $opt{'query'}{'extra_sql'} .=
709 ( $opt{'query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
711 $opt{'count_query'} .=
712 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
715 if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
716 and scalar($curuser->agentnums) > 1 ) {
717 #false laziness w/statuspos above
718 my $pos = $opt{'agent_pos'};
720 foreach my $att (qw( align style color size )) {
721 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
724 splice @{ $opt{'header'} }, $pos, 0, 'Agent';
725 splice @{ $opt{'align'} }, $pos, 0, 'c';
726 splice @{ $opt{'style'} }, $pos, 0, '';
727 splice @{ $opt{'size'} }, $pos, 0, '';
728 splice @{ $opt{'fields'} }, $pos, 0,
729 sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
730 splice @{ $opt{'color'} }, $pos, 0, '';
731 splice @{ $opt{'links'} }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
733 splice @{ $opt{'link_onclicks'} }, $pos, 0, ''
734 if $opt{'link_onclicks'};
740 if ( $opt{'disableable'} ) {
742 unless ( $cgi->param('showdisabled') ) { #modify searches
744 $opt{'query'}{'hashref'}{'disabled'} = '';
745 $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
747 $opt{'count_query'} .=
748 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
749 "( disabled = '' OR disabled IS NULL )";
751 } elsif ( $opt{'disabled_statuspos'}
752 || $opt{'disabled_statuspos'} eq '0' ) { #add status column
754 my $pos = $opt{'disabled_statuspos'};
756 foreach my $att (qw( align style color size )) {
757 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
760 splice @{ $opt{'header'} }, $pos, 0, 'Status';
761 splice @{ $opt{'align'} }, $pos, 0, 'c';
762 splice @{ $opt{'style'} }, $pos, 0, 'b';
763 splice @{ $opt{'size'} }, $pos, 0, '';
764 splice @{ $opt{'fields'} }, $pos, 0,
765 sub { shift->disabled ? 'DISABLED' : 'Active'; };
766 splice @{ $opt{'color'} }, $pos, 0,
767 sub { shift->disabled ? 'FF0000' : '00CC00'; };
768 splice @{ $opt{'links'} }, $pos, 0, ''
770 splice @{ $opt{'link_onlicks'} }, $pos, 0, ''
771 if $opt{'link_onlicks'};
774 #add show/hide disabled links
775 my $items = $opt{'name'} || PL($opt{'name_singular'});
776 if ( $cgi->param('showdisabled') ) {
777 $cgi->param('showdisabled', 0);
778 $opt{'html_posttotal'} .=
779 '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!;
780 $cgi->param('showdisabled', 1);
782 $cgi->param('showdisabled', 1);
783 $opt{'html_posttotal'} .=
784 '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!;
785 $cgi->param('showdisabled', 0);
790 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|select|html(-print)?)$/
794 my($confmax, $maxrecords, $total, $offset, $count_arrayref);
796 unless ( $type =~ /^(csv|\w*\.xls)$/ ) {
798 unless (exists($opt{count_query}) && length($opt{count_query})) {
799 ( $opt{count_query} = $opt{query} ) =~
800 s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
803 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
805 ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
806 "( disabled = '' OR disabled IS NULL )";
809 unless ( $type eq 'html-print' ) {
811 #setup some pagination things if we're in html mode
813 my $conf = new FS::Conf;
814 $confmax = $conf->config('maxsearchrecordsperpage');
815 if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
818 $maxrecords ||= $confmax;
821 $limit = $maxrecords ? "LIMIT $maxrecords" : '';
823 $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
824 $limit .= " OFFSET $offset" if $offset;
828 my $count_sth = dbh->prepare($opt{'count_query'})
829 or die "Error preparing $opt{'count_query'}: ". dbh->errstr;
831 or die "Error executing $opt{'count_query'}: ". $count_sth->errstr;
832 $count_arrayref = $count_sth->fetchrow_arrayref;
833 $total = $count_arrayref->[0];
839 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
841 if ( ref($opt{query}) ) {
843 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
844 #%search = ( 'disabled' => '' );
845 $opt{'query'}->{'hashref'}->{'disabled'} = '';
846 $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
849 #eval "use FS::$opt{'query'};";
851 'select' => $opt{'query'}->{'select'},
852 'table' => $opt{'query'}->{'table'},
853 'addl_from' => (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : ''),
854 'hashref' => $opt{'query'}->{'hashref'} || {},
855 'extra_sql' => $opt{'query'}->{'extra_sql'},
856 'order_by' => $opt{'query'}->{'order_by'}. " $limit",
859 my $sth = dbh->prepare("$opt{'query'} $limit")
860 or die "Error preparing $opt{'query'}: ". dbh->errstr;
862 or die "Error executing $opt{'query'}: ". $sth->errstr;
864 #can get # of rows without fetching them all?
865 $rows = $sth->fetchall_arrayref;
867 $header ||= $sth->{NAME};