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
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'} ) {
344 % my $n=0; foreach my $count ( @{$opt{'count_addl'}} ) {
345 <% sprintf( $count, $count_arrayref->[++$n] ) %><BR>
352 % unless ( $opt{'disable_download'} || $type eq 'html-print' ) {
356 Download full results<BR>
358 % $cgi->param('_type', "$xlsname.xls" );
359 as <A HREF="<% $cgi->self_url %>">Excel spreadsheet</A><BR>
361 % $cgi->param('_type', 'csv');
362 as <A HREF="<% $cgi->self_url %>">CSV file</A><BR>
364 % $cgi->param('_type', 'html-print');
365 as <A HREF="<% $cgi->self_url %>">printable copy</A>
368 % $cgi->param('_type', "html" );
376 % unless ( $type eq 'html_print' ) {
378 <% $pager = include( '/elements/pager.html',
380 'num_rows' => scalar(@$rows),
382 'maxrecords' => $maxrecords,
386 <% defined($opt{'html_form'})
387 ? ( ref($opt{'html_form'})
388 ? &{$opt{'html_form'}}()
396 <% include('/elements/table-grid.html') %>
400 % foreach my $header ( @{ $opt{header} } ) {
401 % my $label = ref($header) ? $header->{label} : $header;
404 % if ( $opt{header2} ) {
405 % if ( !length($opt{header2}->[$h2]) ) {
407 % splice @{ $opt{header2} }, $h2, 1;
410 % $style = 'STYLE="border-bottom: none"'
415 ROWSPAN = "<% $rowspan %>"
424 % if ( $opt{header2} ) {
426 % foreach my $header ( @{ $opt{header2} } ) {
427 % my $label = ref($header) ? $header->{label} : $header;
428 <TH CLASS="grid" BGCOLOR="#cccccc">
429 <FONT SIZE="-1"><% $label %></FONT>
435 % my $bgcolor1 = '#eeeeee';
436 % my $bgcolor2 = '#ffffff';
439 % foreach my $row ( @$rows ) {
441 % if ( $bgcolor eq $bgcolor1 ) {
442 % $bgcolor = $bgcolor2;
444 % $bgcolor = $bgcolor1;
449 % if ( $opt{'fields'} ) {
451 % my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
452 % my $onclicks = $opt{'link_onclicks'} ? [ @{$opt{'link_onclicks'}} ] : [];
453 % my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
454 % my $colors = $opt{'color'} ? [ @{$opt{'color'}} ] : [];
455 % my $sizes = $opt{'size'} ? [ @{$opt{'size'}} ] : [];
456 % my $styles = $opt{'style'} ? [ @{$opt{'style'}} ] : [];
457 % my $cstyles = $opt{'cell_style'} ? [ @{$opt{'cell_style'}} ] : [];
459 % foreach my $field (
462 % if ( ref($_) eq 'ARRAY' ) {
466 % '<TABLE CLASS="inv" CELLSPACING=0 CELLPADDING=0 WIDTH="100%">'.
480 % uc($_).'="'. $e->{$_}. '"';
482 % grep exists($e->{$_}),
483 % qw( align bgcolor colspan rowspan
484 % style valign width )
489 % ? '<A HREF="'. $e->{'link'}. '">'
493 % ? '<FONT SIZE="'.uc($e->{'size'}).'">'
496 % ( $e->{'data_style'}
497 % ? '<'. uc($e->{'data_style'}). '>'
501 % ( $e->{'data_style'}
502 % ? '</'. uc($e->{'data_style'}). '>'
505 % ( $e->{'size'} ? '</FONT>' : '' ).
506 % ( $e->{'link'} ? '</A>' : '' ).
522 % if ( ref($_) eq 'CODE' ) {
532 % my $class = ( $field =~ /^<TABLE/i ) ? 'inv' : 'grid';
534 % my $align = $aligns ? shift @$aligns : '';
535 % $align = " ALIGN=$align" if $align;
539 % my $link = shift @$links;
540 % $link = &{$link}($row)
541 % if ref($link) eq 'CODE';
543 % my $onclick = shift @$onclicks;
544 % $onclick = &{$onclick}($row)
545 % if ref($onclick) eq 'CODE';
546 % $onclick = qq( onClick="$onclick") if $onclick;
549 % my( $url, $method ) = @{$link};
550 % if ( ref($method) eq 'CODE' ) {
551 % $a = $url. &{$method}($row);
553 % $a = $url. $row->$method();
555 % $a = qq(<A HREF="$a"$onclick>);
560 % my $color = shift @$colors;
561 % $color = &{$color}($row) if ref($color) eq 'CODE';
562 % my $size = shift @$sizes;
563 % $size = &{$size}($row) if ref($size) eq 'CODE';
564 % if ( $color || $size ) {
566 % ( $color ? "COLOR=#$color " : '' ).
567 % ( $size ? qq(SIZE="$size" ) : '' ).
571 % my($s, $es) = ( '', '' );
572 % my $style = shift @$styles;
573 % $style = &{$style}($row) if ref($style) eq 'CODE';
575 % $s = join( '', map "<$_>", split('', $style) );
576 % $es = join( '', map "</$_>", split('', $style) );
579 % my $cstyle = shift @$cstyles;
580 % $cstyle = &{$cstyle}($row) if ref($cstyle) eq 'CODE';
581 % $cstyle = qq(STYLE="$cstyle")
584 <TD CLASS="<% $class %>" BGCOLOR="<% $bgcolor %>" <% $align %> <% $cstyle %>><% $font %><% $a %><% $s %><% $field %><% $es %><% $a ? '</A>' : '' %><% $font ? '</FONT>' : '' %></TD>
590 % foreach ( @$row ) {
591 <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $_ %></TD>
600 % if ( $opt{'footer'} ) {
604 % foreach my $footer ( @{ $opt{'footer'} } ) {
605 <TD CLASS="grid" BGCOLOR="#dddddd" STYLE="border-top: dashed 1px black;"><i><% $footer %></i></TD>
620 % if ( $type eq 'html-print' ) {
626 <% defined($opt{'html_foot'})
627 ? ( ref($opt{'html_foot'})
628 ? &{$opt{'html_foot'}}()
634 <% include( '/elements/footer.html' ) %>
644 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
646 my $curuser = $FS::CurrentUser::CurrentUser;
655 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
656 unless !$opt{align} || ref($opt{align});
658 if ( $opt{'agent_virt'} ) {
660 my $agentnums_sql = $curuser->agentnums_sql(
661 'null_right' => $opt{'agent_null_right'}
664 $opt{'query'}{'extra_sql'} .=
665 ( $opt{'query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
667 $opt{'count_query'} .=
668 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
671 if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
672 and scalar($curuser->agentnums) > 1 ) {
673 #false laziness w/statuspos above
674 my $pos = $opt{'agent_pos'};
676 foreach my $att (qw( align style color size )) {
677 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
680 splice @{ $opt{'header'} }, $pos, 0, 'Agent';
681 splice @{ $opt{'align'} }, $pos, 0, 'c';
682 splice @{ $opt{'style'} }, $pos, 0, '';
683 splice @{ $opt{'size'} }, $pos, 0, '';
684 splice @{ $opt{'fields'} }, $pos, 0,
685 sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
686 splice @{ $opt{'color'} }, $pos, 0, '';
687 splice @{ $opt{'links'} }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
689 splice @{ $opt{'link_onclicks'} }, $pos, 0, ''
690 if $opt{'link_onclicks'};
696 if ( $opt{'disableable'} ) {
698 unless ( $cgi->param('showdisabled') ) { #modify searches
700 $opt{'query'}{'hashref'}{'disabled'} = '';
701 $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
703 $opt{'count_query'} .=
704 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
705 "( disabled = '' OR disabled IS NULL )";
707 } elsif ( $opt{'disabled_statuspos'}
708 || $opt{'disabled_statuspos'} eq '0' ) { #add status column
710 my $pos = $opt{'disabled_statuspos'};
712 foreach my $att (qw( align style color size )) {
713 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
716 splice @{ $opt{'header'} }, $pos, 0, 'Status';
717 splice @{ $opt{'align'} }, $pos, 0, 'c';
718 splice @{ $opt{'style'} }, $pos, 0, 'b';
719 splice @{ $opt{'size'} }, $pos, 0, '';
720 splice @{ $opt{'fields'} }, $pos, 0,
721 sub { shift->disabled ? 'DISABLED' : 'Active'; };
722 splice @{ $opt{'color'} }, $pos, 0,
723 sub { shift->disabled ? 'FF0000' : '00CC00'; };
724 splice @{ $opt{'links'} }, $pos, 0, ''
726 splice @{ $opt{'link_onlicks'} }, $pos, 0, ''
727 if $opt{'link_onlicks'};
730 #add show/hide disabled links
731 my $items = $opt{'name'} || PL($opt{'name_singular'});
732 if ( $cgi->param('showdisabled') ) {
733 $cgi->param('showdisabled', 0);
734 $opt{'html_posttotal'} .=
735 '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!;
736 $cgi->param('showdisabled', 1);
738 $cgi->param('showdisabled', 1);
739 $opt{'html_posttotal'} .=
740 '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!;
741 $cgi->param('showdisabled', 0);
746 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|html(-print)?)$/
750 my($confmax, $maxrecords, $total, $offset, $count_arrayref);
752 unless ( $type =~ /^(csv|\w*\.xls)$/ ) {
754 unless (exists($opt{count_query}) && length($opt{count_query})) {
755 ( $opt{count_query} = $opt{query} ) =~
756 s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
759 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
761 ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
762 "( disabled = '' OR disabled IS NULL )";
765 unless ( $type eq 'html-print' ) {
767 #setup some pagination things if we're in html mode
769 my $conf = new FS::Conf;
770 $confmax = $conf->config('maxsearchrecordsperpage');
771 if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
774 $maxrecords ||= $confmax;
777 $limit = $maxrecords ? "LIMIT $maxrecords" : '';
779 $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
780 $limit .= " OFFSET $offset" if $offset;
784 my $count_sth = dbh->prepare($opt{'count_query'})
785 or die "Error preparing $opt{'count_query'}: ". dbh->errstr;
787 or die "Error executing $opt{'count_query'}: ". $count_sth->errstr;
788 $count_arrayref = $count_sth->fetchrow_arrayref;
789 $total = $count_arrayref->[0];
795 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
797 if ( ref($opt{query}) ) {
799 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
800 #%search = ( 'disabled' => '' );
801 $opt{'query'}->{'hashref'}->{'disabled'} = '';
802 $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
805 #eval "use FS::$opt{'query'};";
807 'select' => $opt{'query'}->{'select'},
808 'table' => $opt{'query'}->{'table'},
809 'addl_from' => (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : ''),
810 'hashref' => $opt{'query'}->{'hashref'} || {},
811 'extra_sql' => $opt{'query'}->{'extra_sql'},
812 'order_by' => $opt{'query'}->{'order_by'}. " $limit",
815 my $sth = dbh->prepare("$opt{'query'} $limit")
816 or die "Error preparing $opt{'query'}: ". dbh->errstr;
818 or die "Error executing $opt{'query'}: ". $sth->errstr;
820 #can get # of rows without fetching them all?
821 $rows = $sth->fetchall_arrayref;
823 $header ||= $sth->{NAME};