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>
331 <% $total %> total <% $opt{'name'} %>
333 % if ( $confmax && $total > $confmax && $type ne 'html-print' ) {
334 % $cgi->delete('maxrecords');
335 % $cgi->param('_dummy', 1);
337 %# ( show <SELECT NAME="maxrecords" onChange="this.form.submit();">
338 ( show <SELECT NAME="maxrecords" onChange="window.location = '<% $cgi->self_url %>;maxrecords=' + this.options[this.selectedIndex].value;">
340 % foreach my $max ( map { $_ * $confmax } qw( 1 5 10 25 ) ) {
341 <OPTION VALUE="<% $max %>" <% ( $maxrecords == $max ) ? 'SELECTED' : '' %>><% $max %></OPTION>
346 % $cgi->param('maxrecords', $maxrecords);
349 % if ( defined($opt{'html_posttotal'}) && $type ne 'html-print' ) {
350 <% ref($opt{'html_posttotal'})
351 ? &{$opt{'html_posttotal'}}()
352 : $opt{'html_posttotal'}
357 % if ( $opt{'count_addl'} ) {
359 % foreach my $count ( @{$opt{'count_addl'}} ) {
360 % my $data = $count_arrayref->[++$n];
361 % if ( ref($count) ) {
362 <% &{ $count }( $data ) %>
364 <% sprintf( $count, $data ) %><BR>
372 % unless ( $opt{'disable_download'} || $type eq 'html-print' ) {
376 Download full results<BR>
378 % $cgi->param('_type', "$xlsname.xls" );
379 as <A HREF="<% $cgi->self_url %>">Excel spreadsheet</A><BR>
381 % $cgi->param('_type', 'csv');
382 as <A HREF="<% $cgi->self_url %>">CSV file</A><BR>
384 % $cgi->param('_type', 'html-print');
385 as <A HREF="<% $cgi->self_url %>">printable copy</A>
388 % $cgi->param('_type', "html" );
396 % unless ( $type eq 'html_print' ) {
398 <% $pager = include( '/elements/pager.html',
400 'num_rows' => scalar(@$rows),
402 'maxrecords' => $maxrecords,
406 <% defined($opt{'html_form'})
407 ? ( ref($opt{'html_form'})
408 ? &{$opt{'html_form'}}()
416 <% include('/elements/table-grid.html') %>
420 % foreach my $header ( @{ $opt{header} } ) {
421 % my $label = ref($header) ? $header->{label} : $header;
424 % if ( $opt{header2} ) {
425 % if ( !length($opt{header2}->[$h2]) ) {
427 % splice @{ $opt{header2} }, $h2, 1;
430 % $style = 'STYLE="border-bottom: none"'
435 ROWSPAN = "<% $rowspan %>"
444 % if ( $opt{header2} ) {
446 % foreach my $header ( @{ $opt{header2} } ) {
447 % my $label = ref($header) ? $header->{label} : $header;
448 <TH CLASS="grid" BGCOLOR="#cccccc">
449 <FONT SIZE="-1"><% $label %></FONT>
455 % my $bgcolor1 = '#eeeeee';
456 % my $bgcolor2 = '#ffffff';
459 % foreach my $row ( @$rows ) {
461 % if ( $bgcolor eq $bgcolor1 ) {
462 % $bgcolor = $bgcolor2;
464 % $bgcolor = $bgcolor1;
469 % if ( $opt{'fields'} ) {
471 % my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
472 % my $onclicks = $opt{'link_onclicks'} ? [ @{$opt{'link_onclicks'}} ] : [];
473 % my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
474 % my $colors = $opt{'color'} ? [ @{$opt{'color'}} ] : [];
475 % my $sizes = $opt{'size'} ? [ @{$opt{'size'}} ] : [];
476 % my $styles = $opt{'style'} ? [ @{$opt{'style'}} ] : [];
477 % my $cstyles = $opt{'cell_style'} ? [ @{$opt{'cell_style'}} ] : [];
479 % foreach my $field (
482 % if ( ref($_) eq 'ARRAY' ) {
486 % '<TABLE CLASS="inv" CELLSPACING=0 CELLPADDING=0 WIDTH="100%">'.
500 % uc($_).'="'. $e->{$_}. '"';
502 % grep exists($e->{$_}),
503 % qw( align bgcolor colspan rowspan
504 % style valign width )
509 % ? '<A HREF="'. $e->{'link'}. '">'
513 % ? '<FONT SIZE="'.uc($e->{'size'}).'">'
516 % ( $e->{'data_style'}
517 % ? '<'. uc($e->{'data_style'}). '>'
521 % ( $e->{'data_style'}
522 % ? '</'. uc($e->{'data_style'}). '>'
525 % ( $e->{'size'} ? '</FONT>' : '' ).
526 % ( $e->{'link'} ? '</A>' : '' ).
542 % if ( ref($_) eq 'CODE' ) {
552 % my $class = ( $field =~ /^<TABLE/i ) ? 'inv' : 'grid';
554 % my $align = $aligns ? shift @$aligns : '';
555 % $align = " ALIGN=$align" if $align;
559 % my $link = shift @$links;
560 % $link = &{$link}($row)
561 % if ref($link) eq 'CODE';
563 % my $onclick = shift @$onclicks;
564 % $onclick = &{$onclick}($row)
565 % if ref($onclick) eq 'CODE';
566 % $onclick = qq( onClick="$onclick") if $onclick;
569 % my( $url, $method ) = @{$link};
570 % if ( ref($method) eq 'CODE' ) {
571 % $a = $url. &{$method}($row);
573 % $a = $url. $row->$method();
575 % $a = qq(<A HREF="$a"$onclick>);
580 % my $color = shift @$colors;
581 % $color = &{$color}($row) if ref($color) eq 'CODE';
582 % my $size = shift @$sizes;
583 % $size = &{$size}($row) if ref($size) eq 'CODE';
584 % if ( $color || $size ) {
586 % ( $color ? "COLOR=#$color " : '' ).
587 % ( $size ? qq(SIZE="$size" ) : '' ).
591 % my($s, $es) = ( '', '' );
592 % my $style = shift @$styles;
593 % $style = &{$style}($row) if ref($style) eq 'CODE';
595 % $s = join( '', map "<$_>", split('', $style) );
596 % $es = join( '', map "</$_>", split('', $style) );
599 % my $cstyle = shift @$cstyles;
600 % $cstyle = &{$cstyle}($row) if ref($cstyle) eq 'CODE';
601 % $cstyle = qq(STYLE="$cstyle")
604 <TD CLASS="<% $class %>" BGCOLOR="<% $bgcolor %>" <% $align %> <% $cstyle %>><% $font %><% $a %><% $s %><% $field %><% $es %><% $a ? '</A>' : '' %><% $font ? '</FONT>' : '' %></TD>
610 % foreach ( @$row ) {
611 <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $_ %></TD>
620 % if ( $opt{'footer'} ) {
624 % foreach my $footer ( @{ $opt{'footer'} } ) {
625 <TD CLASS="grid" BGCOLOR="#dddddd" STYLE="border-top: dashed 1px black;"><i><% $footer %></i></TD>
640 % if ( $type eq 'html-print' ) {
646 <% defined($opt{'html_foot'})
647 ? ( ref($opt{'html_foot'})
648 ? &{$opt{'html_foot'}}()
654 <% include( '/elements/footer.html' ) %>
664 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
666 my $curuser = $FS::CurrentUser::CurrentUser;
675 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
676 unless !$opt{align} || ref($opt{align});
678 if ( $opt{'agent_virt'} ) {
680 my $agentnums_sql = $curuser->agentnums_sql(
681 'null_right' => $opt{'agent_null_right'}
684 $opt{'query'}{'extra_sql'} .=
685 ( $opt{'query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
687 $opt{'count_query'} .=
688 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
691 if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
692 and scalar($curuser->agentnums) > 1 ) {
693 #false laziness w/statuspos above
694 my $pos = $opt{'agent_pos'};
696 foreach my $att (qw( align style color size )) {
697 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
700 splice @{ $opt{'header'} }, $pos, 0, 'Agent';
701 splice @{ $opt{'align'} }, $pos, 0, 'c';
702 splice @{ $opt{'style'} }, $pos, 0, '';
703 splice @{ $opt{'size'} }, $pos, 0, '';
704 splice @{ $opt{'fields'} }, $pos, 0,
705 sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
706 splice @{ $opt{'color'} }, $pos, 0, '';
707 splice @{ $opt{'links'} }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
709 splice @{ $opt{'link_onclicks'} }, $pos, 0, ''
710 if $opt{'link_onclicks'};
716 if ( $opt{'disableable'} ) {
718 unless ( $cgi->param('showdisabled') ) { #modify searches
720 $opt{'query'}{'hashref'}{'disabled'} = '';
721 $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
723 $opt{'count_query'} .=
724 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
725 "( disabled = '' OR disabled IS NULL )";
727 } elsif ( $opt{'disabled_statuspos'}
728 || $opt{'disabled_statuspos'} eq '0' ) { #add status column
730 my $pos = $opt{'disabled_statuspos'};
732 foreach my $att (qw( align style color size )) {
733 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
736 splice @{ $opt{'header'} }, $pos, 0, 'Status';
737 splice @{ $opt{'align'} }, $pos, 0, 'c';
738 splice @{ $opt{'style'} }, $pos, 0, 'b';
739 splice @{ $opt{'size'} }, $pos, 0, '';
740 splice @{ $opt{'fields'} }, $pos, 0,
741 sub { shift->disabled ? 'DISABLED' : 'Active'; };
742 splice @{ $opt{'color'} }, $pos, 0,
743 sub { shift->disabled ? 'FF0000' : '00CC00'; };
744 splice @{ $opt{'links'} }, $pos, 0, ''
746 splice @{ $opt{'link_onlicks'} }, $pos, 0, ''
747 if $opt{'link_onlicks'};
750 #add show/hide disabled links
751 my $items = $opt{'name'} || PL($opt{'name_singular'});
752 if ( $cgi->param('showdisabled') ) {
753 $cgi->param('showdisabled', 0);
754 $opt{'html_posttotal'} .=
755 '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!;
756 $cgi->param('showdisabled', 1);
758 $cgi->param('showdisabled', 1);
759 $opt{'html_posttotal'} .=
760 '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!;
761 $cgi->param('showdisabled', 0);
766 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|html(-print)?)$/
770 my($confmax, $maxrecords, $total, $offset, $count_arrayref);
772 unless ( $type =~ /^(csv|\w*\.xls)$/ ) {
774 unless (exists($opt{count_query}) && length($opt{count_query})) {
775 ( $opt{count_query} = $opt{query} ) =~
776 s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
779 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
781 ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
782 "( disabled = '' OR disabled IS NULL )";
785 unless ( $type eq 'html-print' ) {
787 #setup some pagination things if we're in html mode
789 my $conf = new FS::Conf;
790 $confmax = $conf->config('maxsearchrecordsperpage');
791 if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
794 $maxrecords ||= $confmax;
797 $limit = $maxrecords ? "LIMIT $maxrecords" : '';
799 $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
800 $limit .= " OFFSET $offset" if $offset;
804 my $count_sth = dbh->prepare($opt{'count_query'})
805 or die "Error preparing $opt{'count_query'}: ". dbh->errstr;
807 or die "Error executing $opt{'count_query'}: ". $count_sth->errstr;
808 $count_arrayref = $count_sth->fetchrow_arrayref;
809 $total = $count_arrayref->[0];
815 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
817 if ( ref($opt{query}) ) {
819 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
820 #%search = ( 'disabled' => '' );
821 $opt{'query'}->{'hashref'}->{'disabled'} = '';
822 $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
825 #eval "use FS::$opt{'query'};";
827 'select' => $opt{'query'}->{'select'},
828 'table' => $opt{'query'}->{'table'},
829 'addl_from' => (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : ''),
830 'hashref' => $opt{'query'}->{'hashref'} || {},
831 'extra_sql' => $opt{'query'}->{'extra_sql'},
832 'order_by' => $opt{'query'}->{'order_by'}. " $limit",
835 my $sth = dbh->prepare("$opt{'query'} $limit")
836 or die "Error preparing $opt{'query'}: ". dbh->errstr;
838 or die "Error executing $opt{'query'}: ". $sth->errstr;
840 #can get # of rows without fetching them all?
841 $rows = $sth->fetchall_arrayref;
843 $header ||= $sth->{NAME};