]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Search.pm
You can now have multiple rows in your MARC Expert 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         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
144     }
145
146
147     my $page = $cgi->param('page') || 0;
148     my $facet = $cgi->param('facet');
149     my $limit = $self->_get_search_limit;
150     my $loc = $cgi->param('loc') || $ctx->{aou_tree}->()->id;
151     my $offset = $page * $limit;
152     my $metarecord = $cgi->param('metarecord');
153     my $results; 
154
155     my ($query, $site, $depth) = _prepare_biblio_search($cgi, $ctx);
156
157     if ($metarecord) {
158
159         # TODO: other limits, like SVF/format, etc.
160         $results = $U->simplereq(
161             'open-ils.search', 
162             'open-ils.search.biblio.metarecord_to_records',
163             $metarecord, {org => $loc, depth => $depth}
164         );
165
166         # force the metarecord result blob to match the format of regular search results
167         $results->{ids} = [map { [$_] } @{$results->{ids}}]; 
168
169     } else {
170
171         return $self->generic_redirect unless $query;
172
173         # Limit and offset will stay here. Everything else should be part of
174         # the query string, not special args.
175         my $args = {'limit' => $limit, 'offset' => $offset};
176
177         # Stuff these into the TT context so that templates can use them in redrawing forms
178         $ctx->{processed_search_query} = $query;
179
180         $query = "$query $facet" if $facet; # TODO
181
182         $logger->activity("EGWeb: [search] $query");
183
184         try {
185
186             my $method = 'open-ils.search.biblio.multiclass.query';
187             $method .= '.staff' if $ctx->{is_staff};
188             $results = $U->simplereq('open-ils.search', $method, $args, $query, 1);
189
190         } catch Error with {
191             my $err = shift;
192             $logger->error("multiclass search error: $err");
193             $results = {count => 0, ids => []};
194         };
195     }
196
197     my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
198
199     $ctx->{records} = [];
200     $ctx->{search_facets} = {};
201     $ctx->{page_size} = $limit;
202     $ctx->{hit_count} = $results->{count};
203
204     return Apache2::Const::OK if @$rec_ids == 0;
205
206     my ($facets, @data) = $self->get_records_and_facets(
207         $rec_ids, $results->{facet_key}, 
208         {
209             flesh => '{holdings_xml,mra}',
210             site => $site,
211             depth => $depth
212         }
213     );
214
215     # shove recs into context in search results order
216     for my $rec_id (@$rec_ids) {
217         push(
218             @{$ctx->{records}},
219             grep { $_->{id} == $rec_id } @data
220         );
221     }
222
223     $ctx->{search_facets} = $facets;
224
225     return Apache2::Const::OK;
226 }
227
228 # Searching by barcode is a special search that does /not/ respect any other
229 # of the usual search parameters, not even the ones for sorting and paging!
230 sub item_barcode_shortcut {
231     my ($self) = @_;
232
233     my $method = "open-ils.search.multi_home.bib_ids.by_barcode";
234     if (my $search = create OpenSRF::AppSession("open-ils.search")) {
235         my $rec_ids = $search->request(
236             $method, $self->cgi->param("query")
237         )->gather(1);
238
239         if (ref $rec_ids ne 'ARRAY') {
240             if (defined $U->event_code($rec_ids)) {
241                 $self->apache->log->warn(
242                     "$method returned event: " . $U->event_code($rec_ids)
243                 );
244             } else {
245                 $self->apache->log->warn(
246                     "$method returned something unexpected: $rec_ids"
247                 );
248             }
249             return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
250         }
251
252         my ($facets, @data) = $self->get_records_and_facets(
253             $rec_ids, undef, {flesh => "{holdings_xml,mra}"}
254         );
255
256         $self->ctx->{records} = [@data];
257         $self->ctx->{search_facets} = {};
258         $self->ctx->{hit_count} = scalar @data;
259         $self->ctx->{page_size} = $self->ctx->{hit_count};
260
261         return Apache2::Const::OK;
262     } {
263         $self->apache->log->warn("couldn't connect to open-ils.search");
264         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
265     }
266 }
267
268 # like item_barcode_search, this can't take all the usual search params, but
269 # this one will at least do site, limit and page
270 sub marc_expert_search {
271     my ($self) = @_;
272
273     my @tags = $self->cgi->param("tag");
274     my @subfields = $self->cgi->param("subfield");
275     my @terms = $self->cgi->param("term");
276
277     my $query = [];
278     for (my $i = 0; $i < scalar @tags; $i++) {
279         next if ($tags[$i] eq "" || $subfields[$i] eq "" || $terms[$i] eq "");
280         push @$query, {
281             "term" => $terms[$i],
282             "restrict" => [{"tag" => $tags[$i], "subfield" => $subfields[$i]}]
283         };
284     }
285
286     $logger->info("query for expert search: " . Dumper($query));
287     # loc, limit and offset
288     my $page = $self->cgi->param("page") || 0;
289     my $limit = $self->_get_search_limit;
290     my $org_unit = $self->cgi->param("loc") || $self->ctx->{aou_tree}->()->id;
291     my $offset = $page * $limit;
292
293     if (my $search = create OpenSRF::AppSession("open-ils.search")) {
294         my $results = $search->request(
295             "open-ils.search.biblio.marc", {
296                 "searches" => $query, "org_unit" => $org_unit
297             }, $limit, $offset
298         )->gather(1);
299
300         if (defined $U->event_code($results)) {
301             $self->apache->log->warn(
302                 "open-ils.search.biblio.marc returned event: " .
303                 $U->event_code($results)
304             );
305             return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
306         }
307
308         my ($facets, @data) = $self->get_records_and_facets(
309             # filter out nulls that will turn up here
310             [ grep { $_ } @{$results->{ids}} ],
311             undef, {flesh => "{holdings_xml,mra}"}
312         );
313
314         $self->ctx->{records} = [@data];
315         $self->ctx->{search_facets} = {};
316
317         $self->ctx->{page_size} = $limit;
318         $self->ctx->{hit_count} = $results->{count};
319
320         return Apache2::Const::OK;
321     } else {
322         $self->apache->log->warn("couldn't connect to open-ils.search");
323         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
324     }
325 }
326
327 1;