summaryrefslogtreecommitdiff
path: root/httemplate/search/elements/search.html
blob: 730a51aa3dd15522f4f9a664e4855a875e54d5d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
<%doc>

Example:

  <& elements/search.html,

    ###
    # required
    ###

    'title'         => 'Page title',

    'name_singular' => 'item',  #singular name for the records returned
       #OR#                     # (preferred, will be pluralized automatically)
    'name'          => 'items', #plural name for the records returned
                                # (deprecated, will be singularlized
                                #  simplisticly)

    #literal SQL query string (corner cases only) or qsearch hashref or arrayref
    #of qsearch hashrefs for a union of qsearches
    'query'       => {
                       'table'     => 'tablename',
                       #everything else is optional...
                       'hashref'   => { 'field' => 'value',
                                        'field' => { 'op'    => '<',
                                                     'value' => '54',
                                                   },
                                      },
                       'select'    => '*',
                       'addl_from' => '', #'LEFT JOIN othertable USING ( key )',
                       'extra_sql' => '', #'AND otherstuff', #'WHERE onlystuff',
                       'order_by'  => 'ORDER BY something',

                     },
                     # "select * from tablename";
   
    #required (now even if 'query' is an SQL query string)
    'count_query' => 'SELECT COUNT(*) FROM tablename',

    ###
    # recommended / common
    ###

    #listref of column labels, <TH>
    #recommended unless 'query' is an SQL query string
    # (if not specified the database column names will be used) (XXX this is not currently working either)
    'header'      => [ '#',
                       'Item',
                       { 'label' => 'Another Item',

                       },
                     ],

    #listref - each item is a literal column name (or method) or coderef
    #if not specified all columns will be shown (XXX this is not currently working?)
    'fields'      => [
                       'column',
                       sub { my $row = shift; $row->column; },
                     ],

    #redirect if there's only one item...
    # listref of URL base and column name (or method)
    # or a coderef that returns the same
    'redirect' => sub { my( $record, $cgi ) = @_;
                        [ popurl(2).'view/item.html', 'primary_key' ];
                      },

    #redirect if there's no items
    # scalar URL or a coderef that returns a URL
    'redirect_empty' => sub { my( $cgi ) = @_;
                              popurl(2).'view/item.html';
                            },

    ###
    # optional
    ###

    # some HTML callbacks...
    'menubar'          => '', #menubar arrayref
    'html_init'        => '', #after the header/menubar and before the pager
    'html_form'        => '', #after the pager, right before the results
                              # (only shown if there are results)
                              # (use this for any form-opening tag rather than
                              #  html_init, to avoid a nested form)
    'html_foot'        => '', #at the bottom
    'html_posttotal'   => '', #at the bottom
                              # (these three can be strings or coderefs)

    'count_addl' => [], #additional count fields listref of sprintf strings or coderefs
                        # [ $money_char.'%.2f total paid', ],

    #second (smaller) header line, currently only for HTML
    'header2      => [ '#',
                       'Item',
                       { 'label' => 'Another Item',

                       },
                     ],

    #listref of column footers
    'footer'      => [],

    #disabling things
    'disable_download'  => '', # set true to hide the CSV/Excel download links
    'disable_total'     => '', # set true to hide the total"
    'disable_maxselect' => '', # set true to disable record/page selection
    'disable_nonefound' => '', # set true to disable the "No matching Xs found"
                               # message
    'nohtmlheader'      => '', # set true to remove the header and menu bar

    #handling "disabled" fields in the records
    'disableable' => 1,  # set set to 1 (or column position for "disabled"
                         # status col) to enable if this table has a "disabled"
                         # field, to hide disabled records & have
                         # "show disabled/hide disabled" links
                         #(can't be used with a literal query)
    'disabled_statuspos' => 3, #optional position (starting from 0) to insert
                               #a Status column when showing disabled records
                               #(query needs to be a qsearch hashref and
                               # header & fields need to be defined)

    # Agent Virtualization parameters:
    #   In this context, only available if your selected table has agentnum.
    #   You must also include agentnum as a SELECT column in your SQL query,
    #     or experience non-obvious problems
    #
    'agent_virt'            => 1, # set true if this search should be
                                  # agent-virtualized
    'agent_null'            => 1, # set true to view global records always
    'agent_null_right'      => 'Access Right', # optional right to view global
                                               # records
    'agent_null_right_link' => 'Access Right'  # optional right to link to
                                               # global records; defaults to
                                               # same as agent_null_right
    'agent_pos'             => 3, # optional position (starting from 0) to
                                  # insert an Agent column (query needs to be a
                                  # qsearch hashref and header & fields need to
                                  # be defined)

    # sort, link & display properties for fields

    'sort_fields' => [], #optional list of field names or SQL expressions for sorts

    'order_by_sql' => {              #to keep complex SQL expressions out of cgi order_by value,
      'fieldname' => 'sql snippet',  #  maps fields/sort_fields values to sql snippets
    }

    #listref - each item is the empty string,
    #          or a listref of link and method name to append,
    #          or a listref of link and coderef to run and append
    #          or a coderef that returns such a listref
    'links'       => [],

    #listref - each item is the empty string,
    #          or a string onClick handler for the corresponding link
    #          or a coderef that returns string onClick handler
    'link_onclicks' => [],

    #one letter for each column, left/right/center/none
    # or pass a listref with full values: [ 'left', 'right', 'center', '' ]
    'align'       => 'lrc.',

    #listrefs of ( scalars or coderefs )
    # currently only HTML, maybe eventually Excel too
    'color'       => [],
    'size'        => [],
    'style'       => [], #<B> or <I>, etc.
    'cell_style'  => [], #STYLE= attribute of TR, very HTML-specific...

    # Excel-specific listref of ( hashrefs or coderefs )
    # each hashref: http://search.cpan.org/dist/Spreadsheet-WriteExcel/lib/Spreadsheet/WriteExcel.pm#Format_methods_and_Format_properties
    'xls_format' => => [],


    # miscellany
   'download_label' => 'Download this report',
                        # defaults to 'Download full results'
   'link_field'     => 'pkgpart'
                        # will create internal links for each row,
                        # with the value of this field as the NAME attribute
                        # If this is a coderef, will evaluate it, passing the
                        # row as an argument, and use the result as the NAME.
  &>

</%doc>
% # if changing this, also update saved search behavior to match!
% if ( $type eq 'csv' ) {
%
<% include('search-csv.html',  header=>$header, rows=>$rows, opt=>\%opt ) %>
%
% } elsif ( $type =~ /\.xls$/ ) {
%
<& 'search-xls.html',  header=>$header, rows=>$rows, opt=>\%opt &>\
% # prevent the caller from polluting our output stream
% $m->abort;
%
% } elsif ( $type eq 'xml' ) {
%
<% include('search-xml.html',  rows=>$rows, opt=>\%opt ) %>
%
% } else {
%
<% include('search-html.html',
             type           => $type,
             header         => $header,
             rows           => $rows,
             link_agentnums => \@link_agentnums,
             null_link      => $null_link,
             confmax        => $confmax,
             maxrecords     => $maxrecords,
             offset         => $offset,
             totals         => $totals,
             opt            => \%opt
          )
%>
%
% }
<%init>

my(%opt) = @_;
#warn join(' / ', map { "$_ => $opt{$_}" } keys %opt ). "\n";

my $curuser = $FS::CurrentUser::CurrentUser;

$m->comp('/elements/handle_uri_query');

my $type = $cgi->param('_type') =~ /^(csv|\w*\.xls|xml|select|html(-print)?)$/
           ? $1 : 'html' ;

if ( !$curuser->access_right('Download report data') ) {
  $opt{'disable_download'} = 1;
  $type = 'html';
}

# split/map aligns here before doing anything else
my %align = (
  'l' => 'left',
  'r' => 'right',
  'c' => 'center',
  ' ' => '',
  '.' => '',
);

$opt{align} = [ map $align{$_}, split(//, $opt{align}) ],
  unless !$opt{align} || ref($opt{align});

if($type =~ /csv|xls/) {
  my $h = $opt{'header'};
  my @del;
  my $i = 0;
  do {
    if( ref($h->[$i]) and exists($h->[$i]->{'nodownload'}) ) {
      splice(@{$opt{$_}}, $i, 1) foreach
        qw(header footer fields links link_onclicks
           align color size style cell_style xls_format);
    }
    else {
      $i++;
    }
  } while ( exists($h->[$i]) );
}

# wtf?
$opt{disable_download} = 0
  if $opt{disable_download} && $curuser->access_right('Configuration download');

$opt{disable_download} = 1
  if $opt{really_disable_download};

# get our queries ready
my $query = $opt{query} or die "query required";
my $count_query = $opt{count_query} or die "count_query required";
# there was a default count_query but it hasn't worked in about ten years

# set up agent restriction
my @link_agentnums = ();
my $null_link = '';
if ( $opt{'agent_virt'} ) {

  @link_agentnums = $curuser->agentnums;
  $null_link = $curuser->access_right(    $opt{'agent_null_right_link'}
                                       || $opt{'agent_null_right'}      );

  my $agentnums_sql = $curuser->agentnums_sql(
                        'null'       => $opt{'agent_null'},
                        'null_right' => $opt{'agent_null_right'},
                        'table'      => $query->{'table'},
                      );

  # this is ridiculous, but we do have searches where $query has constraints
  # and $count_query doesn't, or vice versa.
  if ( $query->{'extra_sql'} =~ /\bWHERE\b/i or keys %{$query->{hashref}} ) {
    $query->{'extra_sql'} .= " AND $agentnums_sql";
  } else {
    $query->{'extra_sql'} .= " WHERE $agentnums_sql";
  }

  if ( $count_query =~ /\bWHERE\b/i ) {
    $count_query .= " AND $agentnums_sql";
  } else {
    $count_query .= " WHERE $agentnums_sql";
  }

  if ( $opt{'agent_pos'} || $opt{'agent_pos'} eq '0'
       and scalar($curuser->agentnums) > 1           ) {
    #false laziness w/statuspos above
    my $pos = $opt{'agent_pos'};

    foreach my $att (qw( align color size style cell_style xls_format )) {
      $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
    }

    splice @{ $opt{'header'} }, $pos, 0, 'Agent';
    splice @{ $opt{'align'}  }, $pos, 0, 'c';
    splice @{ $opt{'style'}  }, $pos, 0, '';
    splice @{ $opt{'size'}   }, $pos, 0, '';
    splice @{ $opt{'fields'} }, $pos, 0,
      sub { $_[0]->agentnum ? $_[0]->agent->agent : '(global)'; };
    splice @{ $opt{'color'}  }, $pos, 0, '';
    splice @{ $opt{'links'}  }, $pos, 0, '' #[ 'agent link?', 'agentnum' ]
      if $opt{'links'};
    splice @{ $opt{'link_onclicks'}  }, $pos, 0, ''
      if $opt{'link_onclicks'};

  }

}

if ( $opt{'disableable'} ) {

  unless ( $cgi->param('showdisabled') ) { #modify searches

    $query->{'hashref'}{'disabled'} = '';
    $query->{'extra_sql'} =~ s/^\s*\bWHERE\b/ AND/i;

    my $table = $query->{'table'};

    $count_query .=
      ( $count_query =~ /\bWHERE\b/i ? ' AND ' : ' WHERE ' ).
      "( $table.disabled = '' OR $table.disabled IS NULL )";

  } elsif (    $opt{'disabled_statuspos'}
            || $opt{'disabled_statuspos'} eq '0' ) { #add status column

    my $pos = $opt{'disabled_statuspos'};

    foreach my $att (qw( align style color size )) {
      $opt{$att} ||= [ map '', @{ $opt{'fields'} } ];
    }

    splice @{ $opt{'header'} }, $pos, 0, 'Status';
    splice @{ $opt{'align'}  }, $pos, 0, 'c';
    splice @{ $opt{'style'}  }, $pos, 0, 'b';
    splice @{ $opt{'size'}   }, $pos, 0, '';
    splice @{ $opt{'fields'} }, $pos, 0,
      sub { shift->disabled ? 'DISABLED' : 'Active'; };
    splice @{ $opt{'color'}  }, $pos, 0,
      sub { shift->disabled ? 'FF0000'   : '00CC00'; };
    splice @{ $opt{'links'}  }, $pos, 0, ''
      if $opt{'links'};
    splice @{ $opt{'link_onclicks'}  }, $pos, 0, ''
      if $opt{'link_onclicks'};
  }

  #add show/hide disabled links
  my $items = $opt{'name'} || PL($opt{'name_singular'});
  if ( $cgi->param('showdisabled') ) {
    $cgi->param('showdisabled', 0);
    $opt{'html_posttotal'} .=
      '( <a href="'. $cgi->self_url. qq!">hide disabled $items</a> )!; #"
    $cgi->param('showdisabled', 1);
  } else {
    $cgi->param('showdisabled', 1);
    $opt{'html_posttotal'} .=
      '( <a href="'. $cgi->self_url. qq!">show disabled $items</a> )!; #"
    $cgi->param('showdisabled', 0);
  }

}

my $limit = '';
my($confmax, $maxrecords, $offset );

unless ( $type =~ /^(csv|xml|\w*.xls)$/) {
# html mode

  unless ( $type eq 'html-print' ) {

    #setup some pagination things if we're in html mode

    my $conf = new FS::Conf;
    $opt{'disable_maxselect'} ||= $conf->exists('disable_maxselect');
    unless ($opt{'disable_maxselect'}) {
      $confmax = $conf->config('maxsearchrecordsperpage') || 100;
      if ( $cgi->param('maxrecords') =~ /^(\d+)$/ ) {
        $maxrecords = $1;
      } else {
        $maxrecords ||= $confmax;
      }
    }

    $limit = $maxrecords ? "LIMIT $maxrecords" : '';

    $offset = $cgi->param('offset') =~ /^(\d+)$/ ? $1 : 0;
    $limit .= " OFFSET $offset" if $offset;

  }

}

#order by override
my $order_by = $opt{order_by} || '';
$order_by = $cgi->param('order_by') if $cgi->param('order_by');

# run the query

my $header = [ map { ref($_) ? $_->{'label'} : $_ } @{$opt{header}} ];
my $rows;

my ($order_by_key,$order_by_desc) = ($order_by =~ /^\s*(.*?)(\s+DESC)?\s*$/i);
my $union_order_by;
$opt{'order_by_sql'} ||= {};
$order_by_desc ||= '';
$order_by = $opt{'order_by_sql'}{$order_by_key} . $order_by_desc
  if $opt{'order_by_sql'}{$order_by_key};

if ( ref $query ) {
  my @query;
  if (ref($query) eq 'HASH') {
    @query = $query;

    # Assemble peices of order_by information as SQL fragment,
    # store as query->{order_by}
    if ( $order_by ) {
      if ( $query->{'order_by'} ) {
        if ( $query->{'order_by'} =~ /^(\s*ORDER\s+BY\s+)?(\S.*)$/is ) {
          $query->{'order_by'} = "ORDER BY $order_by, $2";
        } else {
          warn "unparsable query order_by: ". $query->{'order_by'};
          die "unparsable query order_by: ". $query->{'order_by'};
        }
      } else {
        $query->{'order_by'} = "ORDER BY $order_by";
      }
    }
    $query->{'order_by'} .= " $limit";

  } elsif (ref($query) eq 'ARRAY') {
    # Presented query is a UNION query, with multiple query references
    @query = @{ $query };

    # Assemble peices of order_by information as SQL fragment,
    # store as $union_order_by.  Omit order_by/limit from individual
    # $query hashrefs, because this is a union query
    #
    # ! Currently, order_by data is only fetched from $cgi->param('order_by')
    # ! for union queries. If it eventually needs to be passed within query
    # ! hashrefs, or as mason template options, would need implemented
    $union_order_by = " ORDER BY $order_by " if $order_by;
    $union_order_by .= " $limit " if $limit;

  } else {
    die "invalid query reference ($query)";
  }

  #eval "use FS::$opt{'query'};";
  my @param = qw( select table addl_from hashref extra_sql order_by debug );
  if ($opt{classname_from_column}) {
    # Perform a union of multiple queries, while using the
    # classname_from_column qsearch union option

    # Constrain hashkeys for each query from @param
    @query = map{
      my $query = $_;
      my $new_query = {};
      $new_query->{$_} = $query->{$_} for @param;
      $new_query;
    } @query;

    $rows = [
      qsearch(
        \@query,
        order_by => $union_order_by,
        classname_from_column => 1,
      )
    ];

  } else {
    # default perform a query with qsearch
    $rows = [ qsearch( [ map { my $query = $_;
                               ({ map { $_ => $query->{$_} } @param });
                             }
                         @query
                       ],
                       #'order_by' => $opt{order_by}. " ". $limit,
                     )
            ];
  }
} else { # not ref $query; plain SQL (still used as of 07/2015)

  $query .= " $limit";
  my $sth = dbh->prepare($query)
    or die "Error preparing $query: ". dbh->errstr;
  $sth->execute
    or die "Error executing $query: ". $sth->errstr;

  $rows = $sth->fetchall_arrayref;
  $header ||= $sth->{NAME};
}

# run the count query to get number of rows and other totals
my $count_sth = dbh->prepare($count_query);
$count_sth->execute
  or die "Error executing '$count_query': ".$count_sth->errstr;
my $totals = $count_sth->fetchrow_arrayref;

push @$rows, $opt{'footer_data'} if $opt{'footer_data'};

</%init>