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 or coderefs
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)
56 { 'label' => 'Another Item',
61 #second (smaller) header line, currently only for HTML
64 { 'label' => 'Another Item',
69 'disable_download' => '', # set true to hide the CSV/Excel download links
70 'disable_nonefound' => '', # set true to disable the "No matching Xs found"
73 'disableable' => 1, # set true if this table has a "disabled" field, to
74 # hide disabled records & have "show disabled" links
75 'disabled_statuspos' => 3, #optional position (starting from 0) to insert
76 #a Status column when showing disabled records
77 #(query needs to be a qsearch hashref and
78 # header & fields need to be defined)
79 'agent_virt' => 1, # set true if this search should be agent-virtualized
80 'agent_null_right' => 'Access Right', #opt. right to view global records
81 'agent_pos' => 3, #optional position (starting from 0) to insert
83 #(query needs to be a qsearch hashref and
84 # header & fields need to be defined)
86 #listref - each item is a literal column name (or method) or coderef
87 #if not specified all columns will be shown
90 sub { my $row = shift; $row->column; },
93 #listref of column footers
96 #listref - each item is the empty string,
97 # or a listref of link and method name to append,
98 # or a listref of link and coderef to run and append
99 # or a coderef that returns such a listref
102 #listref - each item is the empty string,
103 # or a string onClick handler for the corresponding link
104 # or a coderef that returns string onClick handler
105 'link_onclicks' => [],
107 #one letter for each column, left/right/center/none
108 # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
111 #listrefs of ( scalars or coderefs )
112 #currently only HTML, maybe eventually Excel too
115 'style' => [], #<B> or <I>, etc.
116 'cell_style' => [], #STYLE= attribute of TR, very HTML-specific...
118 #redirect if there's only one item...
119 # listref of URL base and column name (or method)
120 # or a coderef that returns the same
123 #set to 1 (or column position for "disabled" status col) to enable
124 #"show disabled/hide disabled" links
125 #(can't be used with a literal query)
131 % if ( $type eq 'csv' ) {
133 % #http_header('Content-Type' => 'text/comma-separated-values' ); #IE chokes
134 % http_header('Content-Type' => 'text/plain' );
136 % my $csv = new Text::CSV_XS { 'always_quote' => 1,
137 % 'eol' => "\n", #"\015\012", #"\012"
140 % $csv->combine(@$header); #or die $csv->status;
145 % foreach my $row ( @$rows ) {
147 % if ( $opt{'fields'} ) {
151 % foreach my $field ( @{$opt{'fields'}} ) {
152 % if ( ref($field) eq 'CODE' ) {
155 % ? '(N/A)' #unimplemented
160 % push @line, $row->$field();
164 % $csv->combine(@line); #or die $csv->status;
167 % $csv->combine(@$row); #or die $csv->status;
176 % #} elsif ( $type eq 'excel' ) {
177 % } elsif ( $type =~ /\.xls$/ ) {
179 % #http_header('Content-Type' => 'application/excel' ); #eww
180 % #http_header('Content-Type' => 'application/msexcel' ); #alas
181 % #http_header('Content-Type' => 'application/x-msexcel' ); #?
183 % #http://support.microsoft.com/kb/199841
184 % http_header('Content-Type' => 'application/vnd.ms-excel' );
186 % #http://support.microsoft.com/kb/812935
187 % #http://support.microsoft.com/kb/323308
188 % $HTML::Mason::Commands::r->headers_out->{'Cache-control'} = 'max-age=0';
191 % my $XLS = new IO::Scalar \$data;
192 % my $workbook = Spreadsheet::WriteExcel->new($XLS)
193 % or die "Error opening .xls file: $!";
195 % my $worksheet = $workbook->add_worksheet(substr($opt{'title'},0,31));
199 % $worksheet->write($r, $c++, $_) foreach @$header;
201 % foreach my $row ( @$rows ) {
205 % if ( $opt{'fields'} ) {
207 % #my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
208 % #my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
210 % foreach my $field ( @{$opt{'fields'}} ) {
211 % #my $align = $aligns ? shift @$aligns : '';
212 % #$align = " ALIGN=$align" if $align;
215 % # my $link = shift @$links;
216 % # $link = &{$link}($row) if ref($link) eq 'CODE';
218 % # my( $url, $method ) = @{$link};
219 % # if ( ref($method) eq 'CODE' ) {
220 % # $a = $url. &{$method}($row);
222 % # $a = $url. $row->$method();
224 % # $a = qq(<A HREF="$a">);
227 % if ( ref($field) eq 'CODE' ) {
228 % foreach my $value ( &{$field}($row) ) {
229 % if ( ref($value) eq 'ARRAY' ) {
230 % $worksheet->write($r, $c++, '(N/A)' ); #unimplemented
232 % $worksheet->write($r, $c++, $value );
236 % $worksheet->write($r, $c++, $row->$field() );
241 % $worksheet->write($r, $c++, $_) foreach @$row;
246 % $workbook->close();# or die "Error creating .xls file: $!";
248 % http_header('Content-Length' => length($data) );
253 % } else { # regular HTML
255 % if ( exists($opt{'redirect'}) && scalar(@$rows) == 1 && $total == 1
256 % && $type ne 'html-print'
258 % my $redirect = $opt{'redirect'};
259 % $redirect = &{$redirect}($rows->[0]) if ref($redirect) eq 'CODE';
260 % my( $url, $method ) = @$redirect;
261 % redirect( $url. $rows->[0]->$method() );
263 % if ( $opt{'name_singular'} ) {
264 % $opt{'name'} = PL($opt{'name_singular'});
266 % ( my $xlsname = $opt{'name'} ) =~ s/\W//g;
267 % if ( $total == 1 ) {
268 % if ( $opt{'name_singular'} ) {
269 % $opt{'name'} = $opt{'name_singular'}
271 % #$opt{'name'} =~ s/s$// if $total == 1;
272 % $opt{'name'} =~ s/((s)e)?s$/$2/ if $total == 1;
276 % if ( $type eq 'html-print' ) {
278 <% include( '/elements/header-popup.html', $opt{'title'} ) %>
283 % if ( $opt{'menubar'} ) {
284 % @menubar = @{ $opt{'menubar'} };
286 % # @menubar = ( 'Main menu' => $p );
289 <% include( '/elements/header.html', $opt{'title'},
290 include( '/elements/menubar.html', @menubar )
294 <% defined($opt{'html_init'})
295 ? ( ref($opt{'html_init'})
296 ? &{$opt{'html_init'}}()
304 % unless ( $total ) {
305 % unless ( $opt{'disable_nonefound'} ) {
306 No matching <% $opt{'name'} %> found.<BR>
317 <% $total %> total <% $opt{'name'} %>
319 % if ( $confmax && $total > $confmax && $type ne 'html-print' ) {
320 % $cgi->delete('maxrecords');
321 % $cgi->param('_dummy', 1);
323 %# ( show <SELECT NAME="maxrecords" onChange="this.form.submit();">
324 ( show <SELECT NAME="maxrecords" onChange="window.location = '<% $cgi->self_url %>;maxrecords=' + this.options[this.selectedIndex].value;">
326 % foreach my $max ( map { $_ * $confmax } qw( 1 5 10 25 ) ) {
327 <OPTION VALUE="<% $max %>" <% ( $maxrecords == $max ) ? 'SELECTED' : '' %>><% $max %></OPTION>
332 % $cgi->param('maxrecords', $maxrecords);
335 % if ( defined($opt{'html_posttotal'}) && $type ne 'html-print' ) {
336 <% ref($opt{'html_posttotal'})
337 ? &{$opt{'html_posttotal'}}()
338 : $opt{'html_posttotal'}
343 % if ( $opt{'count_addl'} ) {
345 % foreach my $count ( @{$opt{'count_addl'}} ) {
346 % my $data = $count_arrayref->[++$n];
347 % if ( ref($count) ) {
348 <% &{ $count }( $data ) %>
350 <% sprintf( $count, $data ) %><BR>
358 % unless ( $opt{'disable_download'} || $type eq 'html-print' ) {
362 Download full results<BR>
364 % $cgi->param('_type', "$xlsname.xls" );
365 as <A HREF="<% $cgi->self_url %>">Excel spreadsheet</A><BR>
367 % $cgi->param('_type', 'csv');
368 as <A HREF="<% $cgi->self_url %>">CSV file</A><BR>
370 % $cgi->param('_type', 'html-print');
371 as <A HREF="<% $cgi->self_url %>">printable copy</A>
374 % $cgi->param('_type', "html" );
382 % unless ( $type eq 'html_print' ) {
384 <% $pager = include( '/elements/pager.html',
386 'num_rows' => scalar(@$rows),
388 'maxrecords' => $maxrecords,
392 <% defined($opt{'html_form'})
393 ? ( ref($opt{'html_form'})
394 ? &{$opt{'html_form'}}()
402 <% include('/elements/table-grid.html') %>
406 % foreach my $header ( @{ $opt{header} } ) {
407 % my $label = ref($header) ? $header->{label} : $header;
410 % if ( $opt{header2} ) {
411 % if ( !length($opt{header2}->[$h2]) ) {
413 % splice @{ $opt{header2} }, $h2, 1;
416 % $style = 'STYLE="border-bottom: none"'
421 ROWSPAN = "<% $rowspan %>"
430 % if ( $opt{header2} ) {
432 % foreach my $header ( @{ $opt{header2} } ) {
433 % my $label = ref($header) ? $header->{label} : $header;
434 <TH CLASS="grid" BGCOLOR="#cccccc">
435 <FONT SIZE="-1"><% $label %></FONT>
441 % my $bgcolor1 = '#eeeeee';
442 % my $bgcolor2 = '#ffffff';
445 % foreach my $row ( @$rows ) {
447 % if ( $bgcolor eq $bgcolor1 ) {
448 % $bgcolor = $bgcolor2;
450 % $bgcolor = $bgcolor1;
455 % if ( $opt{'fields'} ) {
457 % my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
458 % my $onclicks = $opt{'link_onclicks'} ? [ @{$opt{'link_onclicks'}} ] : [];
459 % my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
460 % my $colors = $opt{'color'} ? [ @{$opt{'color'}} ] : [];
461 % my $sizes = $opt{'size'} ? [ @{$opt{'size'}} ] : [];
462 % my $styles = $opt{'style'} ? [ @{$opt{'style'}} ] : [];
463 % my $cstyles = $opt{'cell_style'} ? [ @{$opt{'cell_style'}} ] : [];
465 % foreach my $field (
468 % if ( ref($_) eq 'ARRAY' ) {
472 % '<TABLE CLASS="inv" CELLSPACING=0 CELLPADDING=0 WIDTH="100%">'.
486 % uc($_).'="'. $e->{$_}. '"';
488 % grep exists($e->{$_}),
489 % qw( align bgcolor colspan rowspan
490 % style valign width )
495 % ? '<A HREF="'. $e->{'link'}. '">'
499 % ? '<FONT SIZE="'.uc($e->{'size'}).'">'
502 % ( $e->{'data_style'}
503 % ? '<'. uc($e->{'data_style'}). '>'
507 % ( $e->{'data_style'}
508 % ? '</'. uc($e->{'data_style'}). '>'
511 % ( $e->{'size'} ? '</FONT>' : '' ).
512 % ( $e->{'link'} ? '</A>' : '' ).
528 % if ( ref($_) eq 'CODE' ) {
538 % my $class = ( $field =~ /^<TABLE/i ) ? 'inv' : 'grid';
540 % my $align = $aligns ? shift @$aligns : '';
541 % $align = " ALIGN=$align" if $align;
545 % my $link = shift @$links;
546 % $link = &{$link}($row)
547 % if ref($link) eq 'CODE';
549 % my $onclick = shift @$onclicks;
550 % $onclick = &{$onclick}($row)
551 % if ref($onclick) eq 'CODE';
552 % $onclick = qq( onClick="$onclick") if $onclick;
555 % my( $url, $method ) = @{$link};
556 % if ( ref($method) eq 'CODE' ) {
557 % $a = $url. &{$method}($row);
559 % $a = $url. $row->$method();
561 % $a = qq(<A HREF="$a"$onclick>);
566 % my $color = shift @$colors;
567 % $color = &{$color}($row) if ref($color) eq 'CODE';
568 % my $size = shift @$sizes;
569 % $size = &{$size}($row) if ref($size) eq 'CODE';
570 % if ( $color || $size ) {
572 % ( $color ? "COLOR=#$color " : '' ).
573 % ( $size ? qq(SIZE="$size" ) : '' ).
577 % my($s, $es) = ( '', '' );
578 % my $style = shift @$styles;
579 % $style = &{$style}($row) if ref($style) eq 'CODE';
581 % $s = join( '', map "<$_>", split('', $style) );
582 % $es = join( '', map "</$_>", split('', $style) );
585 % my $cstyle = shift @$cstyles;
586 % $cstyle = &{$cstyle}($row) if ref($cstyle) eq 'CODE';
587 % $cstyle = qq(STYLE="$cstyle")
590 <TD CLASS="<% $class %>" BGCOLOR="<% $bgcolor %>" <% $align %> <% $cstyle %>><% $font %><% $a %><% $s %><% $field %><% $es %><% $a ? '</A>' : '' %><% $font ? '</FONT>' : '' %></TD>
596 % foreach ( @$row ) {
597 <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $_ %></TD>
606 % if ( $opt{'footer'} ) {
610 % foreach my $footer ( @{ $opt{'footer'} } ) {
611 <TD CLASS="grid" BGCOLOR="#dddddd" STYLE="border-top: dashed 1px black;"><i><% $footer %></i></TD>
626 % if ( $type eq 'html-print' ) {
632 <% defined($opt{'html_foot'})
633 ? ( ref($opt{'html_foot'})
634 ? &{$opt{'html_foot'}}()
640 <% include( '/elements/footer.html' ) %>
650 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
652 my $curuser = $FS::CurrentUser::CurrentUser;
661 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
662 unless !$opt{align} || ref($opt{align});
664 if ( $opt{'agent_virt'} ) {
666 my $agentnums_sql = $curuser->agentnums_sql(
667 'null_right' => $opt{'agent_null_right'}
670 $opt{'query'}{'extra_sql'} .=
671 ( $opt{'query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
673 $opt{'count_query'} .=
674 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
677 if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
678 and scalar($curuser->agentnums) > 1 ) {
679 #false laziness w/statuspos above
680 my $pos = $opt{'agent_pos'};
682 foreach my $att (qw( align style color size )) {
683 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
686 splice @{ $opt{'header'} }, $pos, 0, 'Agent';
687 splice @{ $opt{'align'} }, $pos, 0, 'c';
688 splice @{ $opt{'style'} }, $pos, 0, '';
689 splice @{ $opt{'size'} }, $pos, 0, '';
690 splice @{ $opt{'fields'} }, $pos, 0,
691 sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
692 splice @{ $opt{'color'} }, $pos, 0, '';
693 splice @{ $opt{'links'} }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
695 splice @{ $opt{'link_onclicks'} }, $pos, 0, ''
696 if $opt{'link_onclicks'};
702 if ( $opt{'disableable'} ) {
704 unless ( $cgi->param('showdisabled') ) { #modify searches
706 $opt{'query'}{'hashref'}{'disabled'} = '';
707 $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
709 $opt{'count_query'} .=
710 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
711 "( disabled = '' OR disabled IS NULL )";
713 } elsif ( $opt{'disabled_statuspos'}
714 || $opt{'disabled_statuspos'} eq '0' ) { #add status column
716 my $pos = $opt{'disabled_statuspos'};
718 foreach my $att (qw( align style color size )) {
719 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
722 splice @{ $opt{'header'} }, $pos, 0, 'Status';
723 splice @{ $opt{'align'} }, $pos, 0, 'c';
724 splice @{ $opt{'style'} }, $pos, 0, 'b';
725 splice @{ $opt{'size'} }, $pos, 0, '';
726 splice @{ $opt{'fields'} }, $pos, 0,
727 sub { shift->disabled ? 'DISABLED' : 'Active'; };
728 splice @{ $opt{'color'} }, $pos, 0,
729 sub { shift->disabled ? 'FF0000' : '00CC00'; };
730 splice @{ $opt{'links'} }, $pos, 0, ''
732 splice @{ $opt{'link_onlicks'} }, $pos, 0, ''
733 if $opt{'link_onlicks'};
736 #add show/hide disabled links
737 my $items = $opt{'name'} || PL($opt{'name_singular'});
738 if ( $cgi->param('showdisabled') ) {
739 $cgi->param('showdisabled', 0);
740 $opt{'html_posttotal'} .=
741 '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!;
742 $cgi->param('showdisabled', 1);
744 $cgi->param('showdisabled', 1);
745 $opt{'html_posttotal'} .=
746 '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!;
747 $cgi->param('showdisabled', 0);
752 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|html(-print)?)$/
756 my($confmax, $maxrecords, $total, $offset, $count_arrayref);
758 unless ( $type =~ /^(csv|\w*\.xls)$/ ) {
760 unless (exists($opt{count_query}) && length($opt{count_query})) {
761 ( $opt{count_query} = $opt{query} ) =~
762 s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
765 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
767 ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
768 "( disabled = '' OR disabled IS NULL )";
771 unless ( $type eq 'html-print' ) {
773 #setup some pagination things if we're in html mode
775 my $conf = new FS::Conf;
776 $confmax = $conf->config('maxsearchrecordsperpage');
777 if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
780 $maxrecords ||= $confmax;
783 $limit = $maxrecords ? "LIMIT $maxrecords" : '';
785 $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
786 $limit .= " OFFSET $offset" if $offset;
790 my $count_sth = dbh->prepare($opt{'count_query'})
791 or die "Error preparing $opt{'count_query'}: ". dbh->errstr;
793 or die "Error executing $opt{'count_query'}: ". $count_sth->errstr;
794 $count_arrayref = $count_sth->fetchrow_arrayref;
795 $total = $count_arrayref->[0];
801 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
803 if ( ref($opt{query}) ) {
805 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
806 #%search = ( 'disabled' => '' );
807 $opt{'query'}->{'hashref'}->{'disabled'} = '';
808 $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
811 #eval "use FS::$opt{'query'};";
813 'select' => $opt{'query'}->{'select'},
814 'table' => $opt{'query'}->{'table'},
815 'addl_from' => (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : ''),
816 'hashref' => $opt{'query'}->{'hashref'} || {},
817 'extra_sql' => $opt{'query'}->{'extra_sql'},
818 'order_by' => $opt{'query'}->{'order_by'}. " $limit",
821 my $sth = dbh->prepare("$opt{'query'} $limit")
822 or die "Error preparing $opt{'query'}: ". dbh->errstr;
824 or die "Error executing $opt{'query'}: ". $sth->errstr;
826 #can get # of rows without fetching them all?
827 $rows = $sth->fetchall_arrayref;
829 $header ||= $sth->{NAME};