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
115 'agent_null_right' => 'Access Right', # optional right to view global
117 'agent_null_right_link' => 'Access Right' # optional right to link to
118 # global records; defaults to
119 # same as agent_null_right
120 'agent_pos' => 3, # optional position (starting from 0) to
121 # insert an Agent column (query needs to be a
122 # qsearch hashref and header & fields need to
125 # link & display properties for fields
127 #listref - each item is the empty string,
128 # or a listref of link and method name to append,
129 # or a listref of link and coderef to run and append
130 # or a coderef that returns such a listref
133 #listref - each item is the empty string,
134 # or a string onClick handler for the corresponding link
135 # or a coderef that returns string onClick handler
136 'link_onclicks' => [],
138 #one letter for each column, left/right/center/none
139 # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
142 #listrefs of ( scalars or coderefs )
143 #currently only HTML, maybe eventually Excel too
146 'style' => [], #<B> or <I>, etc.
147 'cell_style' => [], #STYLE= attribute of TR, very HTML-specific...
152 % if ( $type eq 'csv' ) {
154 % #http_header('Content-Type' => 'text/comma-separated-values' ); #IE chokes
155 % http_header('Content-Type' => 'text/plain' );
157 % my $csv = new Text::CSV_XS { 'always_quote' => 1,
158 % 'eol' => "\n", #"\015\012", #"\012"
161 % $csv->combine(@$header); #or die $csv->status;
166 % foreach my $row ( @$rows ) {
168 % if ( $opt{'fields'} ) {
172 % foreach my $field ( @{$opt{'fields'}} ) {
173 % if ( ref($field) eq 'CODE' ) {
176 % ? '(N/A)' #unimplemented
181 % push @line, $row->$field();
185 % $csv->combine(@line); #or die $csv->status;
188 % $csv->combine(@$row); #or die $csv->status;
197 % #} elsif ( $type eq 'excel' ) {
198 % } elsif ( $type =~ /\.xls$/ ) {
200 % #http_header('Content-Type' => 'application/excel' ); #eww
201 % #http_header('Content-Type' => 'application/msexcel' ); #alas
202 % #http_header('Content-Type' => 'application/x-msexcel' ); #?
204 % #http://support.microsoft.com/kb/199841
205 % http_header('Content-Type' => 'application/vnd.ms-excel' );
207 % #http://support.microsoft.com/kb/812935
208 % #http://support.microsoft.com/kb/323308
209 % $HTML::Mason::Commands::r->headers_out->{'Cache-control'} = 'max-age=0';
212 % my $XLS = new IO::Scalar \$data;
213 % my $workbook = Spreadsheet::WriteExcel->new($XLS)
214 % or die "Error opening .xls file: $!";
216 % my $worksheet = $workbook->add_worksheet(substr($opt{'title'},0,31));
220 % $worksheet->write($r, $c++, $_) foreach @$header;
222 % foreach my $row ( @$rows ) {
226 % if ( $opt{'fields'} ) {
228 % #my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
229 % #my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
231 % foreach my $field ( @{$opt{'fields'}} ) {
232 % #my $align = $aligns ? shift @$aligns : '';
233 % #$align = " ALIGN=$align" if $align;
236 % # my $link = shift @$links;
237 % # $link = &{$link}($row) if ref($link) eq 'CODE';
239 % # my( $url, $method ) = @{$link};
240 % # if ( ref($method) eq 'CODE' ) {
241 % # $a = $url. &{$method}($row);
243 % # $a = $url. $row->$method();
245 % # $a = qq(<A HREF="$a">);
248 % if ( ref($field) eq 'CODE' ) {
249 % foreach my $value ( &{$field}($row) ) {
250 % if ( ref($value) eq 'ARRAY' ) {
251 % $worksheet->write($r, $c++, '(N/A)' ); #unimplemented
253 % $worksheet->write($r, $c++, $value );
257 % $worksheet->write($r, $c++, $row->$field() );
262 % $worksheet->write($r, $c++, $_) foreach @$row;
267 % $workbook->close();# or die "Error creating .xls file: $!";
269 % http_header('Content-Length' => length($data) );
274 % } else { # regular HTML
276 % if ( exists($opt{'redirect'}) && scalar(@$rows) == 1 && $total == 1
277 % && $type ne 'html-print'
279 % my $redirect = $opt{'redirect'};
280 % $redirect = &{$redirect}($rows->[0]) if ref($redirect) eq 'CODE';
281 % my( $url, $method ) = @$redirect;
282 % redirect( $url. $rows->[0]->$method() );
284 % if ( $opt{'name_singular'} ) {
285 % $opt{'name'} = PL($opt{'name_singular'});
287 % ( my $xlsname = $opt{'name'} ) =~ s/\W//g;
288 % if ( $total == 1 ) {
289 % if ( $opt{'name_singular'} ) {
290 % $opt{'name'} = $opt{'name_singular'}
292 % #$opt{'name'} =~ s/s$// if $total == 1;
293 % $opt{'name'} =~ s/((s)e)?s$/$2/ if $total == 1;
297 % if ( $type eq 'html-print' ) {
299 <% include( '/elements/header-popup.html', $opt{'title'} ) %>
301 % } elsif ( $type eq 'select' ) {
303 <% include( '/elements/header-popup.html', $opt{'title'} ) %>
304 <% defined($opt{'html_init'})
305 ? ( ref($opt{'html_init'})
306 ? &{$opt{'html_init'}}()
315 % if ( $opt{'menubar'} ) {
316 % @menubar = @{ $opt{'menubar'} };
318 % # @menubar = ( 'Main menu' => $p );
321 <% include( '/elements/header.html', $opt{'title'},
322 include( '/elements/menubar.html', @menubar )
326 <% defined($opt{'html_init'})
327 ? ( ref($opt{'html_init'})
328 ? &{$opt{'html_init'}}()
336 % unless ( $total ) {
337 % unless ( $opt{'disable_nonefound'} ) {
338 No matching <% $opt{'name'} %> found.<BR>
342 % if ( $total || $opt{'disableable'} ) { #hmm... and there *are* ones to show??
351 % if (! $opt{'disable_total'}) {
352 <% $total %> total <% $opt{'name'} %>
355 % if ( $confmax && $total > $confmax
356 % && ! $opt{'disable_maxselect'}
357 % && $type ne 'html-print' )
359 % $cgi->delete('maxrecords');
360 % $cgi->param('_dummy', 1);
362 ( show <SELECT NAME="maxrecords" onChange="window.location = '<% $cgi->self_url %>;maxrecords=' + this.options[this.selectedIndex].value;">
364 % foreach my $max ( map { $_ * $confmax } qw( 1 5 10 25 ) ) {
365 <OPTION VALUE="<% $max %>" <% ( $maxrecords == $max ) ? 'SELECTED' : '' %>><% $max %></OPTION>
370 % $cgi->param('maxrecords', $maxrecords);
373 % if ( defined($opt{'html_posttotal'}) && $type ne 'html-print' ) {
374 <% ref($opt{'html_posttotal'})
375 ? &{$opt{'html_posttotal'}}()
376 : $opt{'html_posttotal'}
381 % if ( $opt{'count_addl'} ) {
383 % foreach my $count ( @{$opt{'count_addl'}} ) {
384 % my $data = $count_arrayref->[++$n];
385 % if ( ref($count) ) {
386 <% &{ $count }( $data ) %>
388 <% sprintf( $count, $data ) %><BR>
396 % unless ( $opt{'disable_download'} || $type eq 'html-print' ) {
400 Download full results<BR>
402 % $cgi->param('_type', "$xlsname.xls" );
403 as <A HREF="<% $cgi->self_url %>">Excel spreadsheet</A><BR>
405 % $cgi->param('_type', 'csv');
406 as <A HREF="<% $cgi->self_url %>">CSV file</A><BR>
408 % $cgi->param('_type', 'html-print');
409 as <A HREF="<% $cgi->self_url %>">printable copy</A>
411 <% $opt{'extra_choices_callback'}
412 ? &{$opt{'extra_choices_callback'}}($cgi->query_string)
417 % $cgi->param('_type', "html" );
425 % unless ( $type eq 'html_print' ) {
427 <% $pager = include( '/elements/pager.html',
429 'num_rows' => scalar(@$rows),
431 'maxrecords' => $maxrecords,
435 <% defined($opt{'html_form'})
436 ? ( ref($opt{'html_form'})
437 ? &{$opt{'html_form'}}()
445 <% include('/elements/table-grid.html') %>
449 % foreach my $header ( @{ $opt{header} } ) {
450 % my $label = ref($header) ? $header->{label} : $header;
453 % if ( $opt{header2} ) {
454 % if ( !length($opt{header2}->[$h2]) ) {
456 % splice @{ $opt{header2} }, $h2, 1;
459 % $style = 'STYLE="border-bottom: none"'
464 ROWSPAN = "<% $rowspan %>"
473 % if ( $opt{header2} ) {
475 % foreach my $header ( @{ $opt{header2} } ) {
476 % my $label = ref($header) ? $header->{label} : $header;
477 <TH CLASS="grid" BGCOLOR="#cccccc">
478 <FONT SIZE="-1"><% $label %></FONT>
484 % my $bgcolor1 = '#eeeeee';
485 % my $bgcolor2 = '#ffffff';
488 % foreach my $row ( @$rows ) {
490 % if ( $bgcolor eq $bgcolor1 ) {
491 % $bgcolor = $bgcolor2;
493 % $bgcolor = $bgcolor1;
498 % if ( $opt{'fields'} ) {
500 % my $links = $opt{'links'} ? [ @{$opt{'links'}} ] : '';
501 % my $onclicks = $opt{'link_onclicks'} ? [ @{$opt{'link_onclicks'}} ] : [];
502 % my $aligns = $opt{'align'} ? [ @{$opt{'align'}} ] : '';
503 % my $colors = $opt{'color'} ? [ @{$opt{'color'}} ] : [];
504 % my $sizes = $opt{'size'} ? [ @{$opt{'size'}} ] : [];
505 % my $styles = $opt{'style'} ? [ @{$opt{'style'}} ] : [];
506 % my $cstyles = $opt{'cell_style'} ? [ @{$opt{'cell_style'}} ] : [];
508 % foreach my $field (
511 % if ( ref($_) eq 'ARRAY' ) {
515 % '<TABLE CLASS="inv" CELLSPACING=0 CELLPADDING=0 WIDTH="100%">'.
529 % uc($_).'="'. $e->{$_}. '"';
531 % grep exists($e->{$_}),
532 % qw( align bgcolor colspan rowspan
533 % style valign width )
538 % ? '<A HREF="'. $e->{'link'}. '">'
542 % ? '<FONT SIZE="'.uc($e->{'size'}).'">'
545 % ( $e->{'data_style'}
546 % ? '<'. uc($e->{'data_style'}). '>'
550 % ( $e->{'data_style'}
551 % ? '</'. uc($e->{'data_style'}). '>'
554 % ( $e->{'size'} ? '</FONT>' : '' ).
555 % ( $e->{'link'} ? '</A>' : '' ).
571 % if ( ref($_) eq 'CODE' ) {
581 % my $class = ( $field =~ /^<TABLE/i ) ? 'inv' : 'grid';
583 % my $align = $aligns ? shift @$aligns : '';
584 % $align = " ALIGN=$align" if $align;
588 % my $link = shift @$links;
589 % my $onclick = shift @$onclicks;
591 % if ( ! $opt{'agent_virt'}
592 % || ( $null_link && ! $row->agentnum )
593 % || grep { $row->agentnum == $_ }
597 % $link = &{$link}($row)
598 % if ref($link) eq 'CODE';
600 % $onclick = &{$onclick}($row)
601 % if ref($onclick) eq 'CODE';
602 % $onclick = qq( onClick="$onclick") if $onclick;
605 % my( $url, $method ) = @{$link};
606 % if ( ref($method) eq 'CODE' ) {
607 % $a = $url. &{$method}($row);
609 % $a = $url. $row->$method();
611 % $a = qq(<A HREF="$a"$onclick>);
619 % my $color = shift @$colors;
620 % $color = &{$color}($row) if ref($color) eq 'CODE';
621 % my $size = shift @$sizes;
622 % $size = &{$size}($row) if ref($size) eq 'CODE';
623 % if ( $color || $size ) {
625 % ( $color ? "COLOR=#$color " : '' ).
626 % ( $size ? qq(SIZE="$size" ) : '' ).
630 % my($s, $es) = ( '', '' );
631 % my $style = shift @$styles;
632 % $style = &{$style}($row) if ref($style) eq 'CODE';
634 % $s = join( '', map "<$_>", split('', $style) );
635 % $es = join( '', map "</$_>", split('', $style) );
638 % my $cstyle = shift @$cstyles;
639 % $cstyle = &{$cstyle}($row) if ref($cstyle) eq 'CODE';
640 % $cstyle = qq(STYLE="$cstyle")
643 <TD CLASS="<% $class %>" BGCOLOR="<% $bgcolor %>" <% $align %> <% $cstyle %>><% $font %><% $a %><% $s %><% $field %><% $es %><% $a ? '</A>' : '' %><% $font ? '</FONT>' : '' %></TD>
649 % foreach ( @$row ) {
650 <TD CLASS="grid" BGCOLOR="<% $bgcolor %>"><% $_ %></TD>
659 % if ( $opt{'footer'} ) {
663 % foreach my $footer ( @{ $opt{'footer'} } ) {
664 <TD CLASS="grid" BGCOLOR="#dddddd" STYLE="border-top: dashed 1px black;"><i><% $footer %></i></TD>
679 % if ( $type eq 'html-print' ) {
685 <% defined($opt{'html_foot'})
686 ? ( ref($opt{'html_foot'})
687 ? &{$opt{'html_foot'}}()
693 <% include( '/elements/footer.html' ) %>
703 #warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";
705 my $curuser = $FS::CurrentUser::CurrentUser;
714 $opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
715 unless !$opt{align} || ref($opt{align});
717 $opt{disable_download} = 0
718 if $opt{disable_download} && $curuser->access_right('Configuration download');
720 my @link_agentnums = ();
722 if ( $opt{'agent_virt'} ) {
724 @link_agentnums = $curuser->agentnums;
725 $null_link = $curuser->access_right( $opt{'agent_null_right_link'}
726 || $opt{'agent_null_right'} );
728 my $agentnums_sql = $curuser->agentnums_sql(
729 'null_right' => $opt{'agent_null_right'}
732 $opt{'query'}{'extra_sql'} .=
733 ( $opt{'query'}{'extra_sql'} =~ /WHERE/i || keys %{$opt{'query'}{'hashref'}}
735 : ' WHERE ' ). $agentnums_sql;
737 $opt{'count_query'} .=
738 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ). $agentnums_sql;
740 if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
741 and scalar($curuser->agentnums) > 1 ) {
742 #false laziness w/statuspos above
743 my $pos = $opt{'agent_pos'};
745 foreach my $att (qw( align style color size )) {
746 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
749 splice @{ $opt{'header'} }, $pos, 0, 'Agent';
750 splice @{ $opt{'align'} }, $pos, 0, 'c';
751 splice @{ $opt{'style'} }, $pos, 0, '';
752 splice @{ $opt{'size'} }, $pos, 0, '';
753 splice @{ $opt{'fields'} }, $pos, 0,
754 sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
755 splice @{ $opt{'color'} }, $pos, 0, '';
756 splice @{ $opt{'links'} }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
758 splice @{ $opt{'link_onclicks'} }, $pos, 0, ''
759 if $opt{'link_onclicks'};
765 if ( $opt{'disableable'} ) {
767 unless ( $cgi->param('showdisabled') ) { #modify searches
769 $opt{'query'}{'hashref'}{'disabled'} = '';
770 $opt{'query'}{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
772 $opt{'count_query'} .=
773 ( $opt{'count_query'} =~ /WHERE/i ? ' AND ' : ' WHERE ' ).
774 "( disabled = '' OR disabled IS NULL )";
776 } elsif ( $opt{'disabled_statuspos'}
777 || $opt{'disabled_statuspos'} eq '0' ) { #add status column
779 my $pos = $opt{'disabled_statuspos'};
781 foreach my $att (qw( align style color size )) {
782 $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
785 splice @{ $opt{'header'} }, $pos, 0, 'Status';
786 splice @{ $opt{'align'} }, $pos, 0, 'c';
787 splice @{ $opt{'style'} }, $pos, 0, 'b';
788 splice @{ $opt{'size'} }, $pos, 0, '';
789 splice @{ $opt{'fields'} }, $pos, 0,
790 sub { shift->disabled ? 'DISABLED' : 'Active'; };
791 splice @{ $opt{'color'} }, $pos, 0,
792 sub { shift->disabled ? 'FF0000' : '00CC00'; };
793 splice @{ $opt{'links'} }, $pos, 0, ''
795 splice @{ $opt{'link_onlicks'} }, $pos, 0, ''
796 if $opt{'link_onlicks'};
799 #add show/hide disabled links
800 my $items = $opt{'name'} || PL($opt{'name_singular'});
801 if ( $cgi->param('showdisabled') ) {
802 $cgi->param('showdisabled', 0);
803 $opt{'html_posttotal'} .=
804 '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!;
805 $cgi->param('showdisabled', 1);
807 $cgi->param('showdisabled', 1);
808 $opt{'html_posttotal'} .=
809 '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!;
810 $cgi->param('showdisabled', 0);
815 my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|select|html(-print)?)$/
819 my($confmax, $maxrecords, $total, $offset, $count_arrayref);
821 unless ( $type =~ /^(csv|\w*\.xls)$/ ) {
823 unless (exists($opt{count_query}) && length($opt{count_query})) {
824 ( $opt{count_query} = $opt{query} ) =~
825 s/^\s*SELECT\s*(.*?)\s+FROM\s/SELECT COUNT(*) FROM /i; #silly vim:/
828 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
830 ( ( $opt{count_query} =~ /WHERE/i ) ? ' AND ' : ' WHERE ' ).
831 "( disabled = '' OR disabled IS NULL )";
834 unless ( $type eq 'html-print' ) {
836 #setup some pagination things if we're in html mode
838 my $conf = new FS::Conf;
839 $confmax = $conf->config('maxsearchrecordsperpage');
840 if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
843 $maxrecords ||= $confmax;
846 $limit = $maxrecords ? "LIMIT $maxrecords" : '';
848 $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
849 $limit .= " OFFSET $offset" if $offset;
853 my $count_sth = dbh->prepare($opt{'count_query'})
854 or die "Error preparing $opt{'count_query'}: ". dbh->errstr;
856 or die "Error executing $opt{'count_query'}: ". $count_sth->errstr;
857 $count_arrayref = $count_sth->fetchrow_arrayref;
858 $total = $count_arrayref->[0];
864 my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
866 if ( ref($opt{query}) ) {
868 if ( $opt{disableable} && ! $cgi->param('showdisabled') ) {
869 #%search = ( 'disabled' => '' );
870 $opt{'query'}->{'hashref'}->{'disabled'} = '';
871 $opt{'query'}->{'extra_sql'} =~ s/^\s*WHERE/ AND/i;
874 #eval "use FS::$opt{'query'};";
876 'select' => $opt{'query'}->{'select'},
877 'table' => $opt{'query'}->{'table'},
878 'addl_from' => (exists($opt{'query'}->{'addl_from'}) ? $opt{'query'}->{'addl_from'} : ''),
879 'hashref' => $opt{'query'}->{'hashref'} || {},
880 'extra_sql' => $opt{'query'}->{'extra_sql'},
881 'order_by' => $opt{'query'}->{'order_by'}. " $limit",
884 my $sth = dbh->prepare("$opt{'query'} $limit")
885 or die "Error preparing $opt{'query'}: ". dbh->errstr;
887 or die "Error executing $opt{'query'}: ". $sth->errstr;
889 #can get # of rows without fetching them all?
890 $rows = $sth->fetchall_arrayref;
892 $header ||= $sth->{NAME};