]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Search.pm
item_barcode had broken the rest of numeric search
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGCatLoader / Search.pm
1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
3 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
4 use OpenSRF::Utils::Logger qw/$logger/;
5 use OpenILS::Utils::CStoreEditor qw/:funcs/;
6 use OpenILS::Utils::Fieldmapper;
7 use OpenILS::Application::AppUtils;
8 use OpenSRF::Utils::JSON;
9 use Data::Dumper;
10 $Data::Dumper::Indent = 0;
11 my $U = 'OpenILS::Application::AppUtils';
12
13
14 sub _prepare_biblio_search_basics {
15     my ($cgi) = @_;
16
17     return $cgi->param('query') unless $cgi->param('qtype');
18
19     my %parts;
20     my @part_names = qw/qtype contains query/;
21     $parts{$_} = [ $cgi->param($_) ] for (@part_names);
22
23     my @chunks = ();
24     for (my $i = 0; $i < scalar @{$parts{'qtype'}}; $i++) {
25         my ($qtype, $contains, $query) = map { $parts{$_}->[$i] } @part_names;
26
27         next unless $query =~ /\S/;
28         push(@chunks, $qtype . ':') unless $qtype eq 'keyword' and $i == 0;
29
30         # This stuff probably will need refined or rethought to better handle
31         # the weird things Real Users will surely type in.
32         $contains = "" unless defined $contains; # silence warning
33         if ($contains eq 'nocontains') {
34             $query =~ s/"//g;
35             $query = ('"' . $query . '"') if index $query, ' ';
36             $query = '-' . $query;
37         } elsif ($contains eq 'phrase') {
38             $query =~ s/"//g;
39             $query = ('"' . $query . '"') if index $query, ' ';
40         } elsif ($contains eq 'exact') {
41             $query =~ s/[\^\$]//g;
42             $query = '^' . $query . '$';
43         }
44         push @chunks, $query;
45     }
46
47     return join(' ', @chunks);
48 }
49
50 sub _prepare_biblio_search {
51     my ($cgi, $ctx) = @_;
52
53     my $query = _prepare_biblio_search_basics($cgi) || '';
54
55     $query = ('#' . $_ . ' ' . $query) foreach ($cgi->param('modifier'));
56
57     # filters
58     foreach (grep /^fi:/, $cgi->param) {
59         /:(-?\w+)$/ or next;
60         my $term = join(",", $cgi->param($_));
61         $query .= " $1($term)" if length $term;
62     }
63
64     if ($cgi->param('sort')) {
65         my ($axis, $desc) = split /\./, $cgi->param('sort');
66         $query .= " sort($axis)";
67         $query .= '#descending' if $desc;
68     }
69
70     if ($cgi->param('pubdate') && $cgi->param('date1')) {
71         if ($cgi->param('pubdate') eq 'between') {
72             $query .= ' between(' . $cgi->param('date1');
73             $query .= ',' .  $cgi->param('date2') if $cgi->param('date2');
74             $query .= ')';
75         } elsif ($cgi->param('pubdate') eq 'is') {
76             $query .= ' between(' . $cgi->param('date1') .
77                 ',' .  $cgi->param('date1') . ')';  # sic, date1 twice
78         } else {
79             $query .= ' ' . $cgi->param('pubdate') .
80                 '(' . $cgi->param('date1') . ')';
81         }
82     }
83
84     my $site;
85     my $org = $cgi->param('loc');
86     if (defined($org) and $org ne '' and ($org ne $ctx->{aou_tree}->()->id) and not $query =~ /site\(\S+\)/) {
87         $site = $ctx->{get_aou}->($org)->shortname;
88         $query .= " site($site)";
89     }
90
91     if(!$site) {
92         ($site) = ($query =~ /site\(([^\)]+)\)/);
93         $site ||= $ctx->{aou_tree}->()->shortname;
94     }
95
96
97     my $depth;
98     if (defined($cgi->param('depth')) and not $query =~ /depth\(\d+\)/) {
99         $depth = defined $cgi->param('depth') ?
100             $cgi->param('depth') : $ctx->{get_aou}->($site)->ou_type->depth;
101         $query .= " depth($depth)";
102     }
103
104     return ($query, $site, $depth);
105 }
106
107 sub _get_search_limit {
108     my $self = shift;
109
110     # param takes precedence
111     my $limit = $self->cgi->param('limit');
112     return $limit if $limit;
113
114     if($self->editor->requestor) {
115         # See if the user has a hit count preference
116         my $lset = $self->editor->search_actor_user_setting({
117             usr => $self->editor->requestor->id, 
118             name => 'opac.hits_per_page'
119         })->[0];
120         return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
121     }
122
123     return 10; # default
124 }
125
126 # context additions: 
127 #   page_size
128 #   hit_count
129 #   records : list of bre's and copy-count objects
130 sub load_rresults {
131     my $self = shift;
132     my $cgi = $self->cgi;
133     my $ctx = $self->ctx;
134     my $e = $self->editor;
135
136     $ctx->{page} = 'rresult';
137
138     if ($cgi->param("_special")) {
139         return $self->marc_expert_search if scalar($cgi->param("tag"));
140         return $self->item_barcode_shortcut if (
141             $cgi->param("qtype") and ($cgi->param("qtype") eq "item_barcode")
142         );
143     }
144
145     my $page = $cgi->param('page') || 0;
146     my $facet = $cgi->param('facet');
147     my $limit = $self->_get_search_limit;
148     my $loc = $cgi->param('loc') || $ctx->{aou_tree}->()->id;
149     my $offset = $page * $limit;
150     my $metarecord = $cgi->param('metarecord');
151     my $results; 
152
153     my ($query, $site, $depth) = _prepare_biblio_search($cgi, $ctx);
154
155     if ($metarecord) {
156
157         # TODO: other limits, like SVF/format, etc.
158         $results = $U->simplereq(
159             'open-ils.search', 
160             'open-ils.search.biblio.metarecord_to_records',
161             $metarecord, {org => $loc, depth => $depth}
162         );
163
164         # force the metarecord result blob to match the format of regular search results
165         $results->{ids} = [map { [$_] } @{$results->{ids}}]; 
166
167     } else {
168
169         return $self->generic_redirect unless $query;
170
171         # Limit and offset will stay here. Everything else should be part of
172         # the query string, not special args.
173         my $args = {'limit' => $limit, 'offset' => $offset};
174
175         # Stuff these into the TT context so that templates can use them in redrawing forms
176         $ctx->{processed_search_query} = $query;
177
178         $query = "$query $facet" if $facet; # TODO
179
180         $logger->activity("EGWeb: [search] $query");
181
182         try {
183
184             my $method = 'open-ils.search.biblio.multiclass.query';
185             $method .= '.staff' if $ctx->{is_staff};
186             $results = $U->simplereq('open-ils.search', $method, $args, $query, 1);
187
188         } catch Error with {
189             my $err = shift;
190             $logger->error("multiclass search error: $err");
191             $results = {count => 0, ids => []};
192         };
193     }
194
195     my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
196
197     $ctx->{records} = [];
198     $ctx->{search_facets} = {};
199     $ctx->{page_size} = $limit;
200     $ctx->{hit_count} = $results->{count};
201
202     return Apache2::Const::OK if @$rec_ids == 0;
203
204     my ($facets, @data) = $self->get_records_and_facets(
205         $rec_ids, $results->{facet_key}, 
206         {
207             flesh => '{holdings_xml,mra}',
208             site => $site,
209             depth => $depth
210         }
211     );
212
213     # shove recs into context in search results order
214     for my $rec_id (@$rec_ids) {
215         push(
216             @{$ctx->{records}},
217             grep { $_->{id} == $rec_id } @data
218         );
219     }
220
221     $ctx->{search_facets} = $facets;
222
223     return Apache2::Const::OK;
224 }
225
226 # Searching by barcode is a special search that does /not/ respect any other
227 # of the usual search parameters, not even the ones for sorting and paging!
228 sub item_barcode_shortcut {
229     my ($self) = @_;
230
231     my $method = "open-ils.search.multi_home.bib_ids.by_barcode";
232     if (my $search = create OpenSRF::AppSession("open-ils.search")) {
233         my $rec_ids = $search->request(
234             $method, $self->cgi->param("query")
235         )->gather(1);
236
237         if (ref $rec_ids ne 'ARRAY') {
238
239             if($U->event_equals($rec_ids, 'ASSET_COPY_NOT_FOUND')) {
240                 $rec_ids = [];
241
242             } else {
243                 if (defined $U->event_code($rec_ids)) {
244                     $self->apache->log->warn(
245                         "$method returned event: " . $U->event_code($rec_ids)
246                     );
247                 } else {
248                     $self->apache->log->warn(
249                         "$method returned something unexpected: $rec_ids"
250                     );
251                 }
252                 return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
253             }
254         }
255
256         my ($facets, @data) = $self->get_records_and_facets(
257             $rec_ids, undef, {flesh => "{holdings_xml,mra}"}
258         );
259
260         $self->ctx->{records} = [@data];
261         $self->ctx->{search_facets} = {};
262         $self->ctx->{hit_count} = scalar @data;
263         $self->ctx->{page_size} = $self->ctx->{hit_count};
264
265         return Apache2::Const::OK;
266     } {
267         $self->apache->log->warn("couldn't connect to open-ils.search");
268         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
269     }
270 }
271
272 # like item_barcode_search, this can't take all the usual search params, but
273 # this one will at least do site, limit and page
274 sub marc_expert_search {
275     my ($self) = @_;
276
277     my @tags = $self->cgi->param("tag");
278     my @subfields = $self->cgi->param("subfield");
279     my @terms = $self->cgi->param("term");
280
281     my $query = [];
282     for (my $i = 0; $i < scalar @tags; $i++) {
283         next if ($tags[$i] eq "" || $subfields[$i] eq "" || $terms[$i] eq "");
284         push @$query, {
285             "term" => $terms[$i],
286             "restrict" => [{"tag" => $tags[$i], "subfield" => $subfields[$i]}]
287         };
288     }
289
290     $logger->info("query for expert search: " . Dumper($query));
291     # loc, limit and offset
292     my $page = $self->cgi->param("page") || 0;
293     my $limit = $self->_get_search_limit;
294     my $org_unit = $self->cgi->param("loc") || $self->ctx->{aou_tree}->()->id;
295     my $offset = $page * $limit;
296
297     if (my $search = create OpenSRF::AppSession("open-ils.search")) {
298         my $results = $search->request(
299             "open-ils.search.biblio.marc", {
300                 "searches" => $query, "org_unit" => $org_unit
301             }, $limit, $offset
302         )->gather(1);
303
304         if (defined $U->event_code($results)) {
305             $self->apache->log->warn(
306                 "open-ils.search.biblio.marc returned event: " .
307                 $U->event_code($results)
308             );
309             return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
310         }
311
312         my ($facets, @data) = $self->get_records_and_facets(
313             # filter out nulls that will turn up here
314             [ grep { $_ } @{$results->{ids}} ],
315             undef, {flesh => "{holdings_xml,mra}"}
316         );
317
318         $self->ctx->{records} = [@data];
319         $self->ctx->{search_facets} = {};
320
321         $self->ctx->{page_size} = $limit;
322         $self->ctx->{hit_count} = $results->{count};
323
324         return Apache2::Const::OK;
325     } else {
326         $self->apache->log->warn("couldn't connect to open-ils.search");
327         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
328     }
329 }
330
331 1;