]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Search.pm
MARC expert search working
[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 my $U = 'OpenILS::Application::AppUtils';
10
11
12 sub _prepare_biblio_search_basics {
13     my ($cgi) = @_;
14
15     return $cgi->param('query') unless $cgi->param('qtype');
16
17     my %parts;
18     my @part_names = qw/qtype contains query/;
19     $parts{$_} = [ $cgi->param($_) ] for (@part_names);
20
21     my @chunks = ();
22     for (my $i = 0; $i < scalar @{$parts{'qtype'}}; $i++) {
23         my ($qtype, $contains, $query) = map { $parts{$_}->[$i] } @part_names;
24
25         next unless $query =~ /\S/;
26         push(@chunks, $qtype . ':') unless $qtype eq 'keyword' and $i == 0;
27
28         # This stuff probably will need refined or rethought to better handle
29         # the weird things Real Users will surely type in.
30         $contains = "" unless defined $contains; # silence warning
31         if ($contains eq 'nocontains') {
32             $query =~ s/"//g;
33             $query = ('"' . $query . '"') if index $query, ' ';
34             $query = '-' . $query;
35         } elsif ($contains eq 'phrase') {
36             $query =~ s/"//g;
37             $query = ('"' . $query . '"') if index $query, ' ';
38         } elsif ($contains eq 'exact') {
39             $query =~ s/[\^\$]//g;
40             $query = '^' . $query . '$';
41         }
42         push @chunks, $query;
43     }
44
45     return join(' ', @chunks);
46 }
47
48 sub _prepare_biblio_search {
49     my ($cgi, $ctx) = @_;
50
51     my $query = _prepare_biblio_search_basics($cgi) || '';
52
53     $query = ('#' . $_ . ' ' . $query) foreach ($cgi->param('modifier'));
54
55     # filters
56     foreach (grep /^fi:/, $cgi->param) {
57         /:(-?\w+)$/ or next;
58         my $term = join(",", $cgi->param($_));
59         $query .= " $1($term)" if length $term;
60     }
61
62     if ($cgi->param('sort')) {
63         my ($axis, $desc) = split /\./, $cgi->param('sort');
64         $query .= " sort($axis)";
65         $query .= '#descending' if $desc;
66     }
67
68     if ($cgi->param('pubdate') && $cgi->param('date1')) {
69         if ($cgi->param('pubdate') eq 'between') {
70             $query .= ' between(' . $cgi->param('date1');
71             $query .= ',' .  $cgi->param('date2') if $cgi->param('date2');
72             $query .= ')';
73         } elsif ($cgi->param('pubdate') eq 'is') {
74             $query .= ' between(' . $cgi->param('date1') .
75                 ',' .  $cgi->param('date1') . ')';  # sic, date1 twice
76         } else {
77             $query .= ' ' . $cgi->param('pubdate') .
78                 '(' . $cgi->param('date1') . ')';
79         }
80     }
81
82     my $site;
83     my $org = $cgi->param('loc');
84     if (defined($org) and $org ne '' and ($org ne $ctx->{aou_tree}->()->id) and not $query =~ /site\(\S+\)/) {
85         $site = $ctx->{get_aou}->($org)->shortname;
86         $query .= " site($site)";
87     }
88
89     if(!$site) {
90         ($site) = ($query =~ /site\(([^\)]+)\)/);
91         $site ||= $ctx->{aou_tree}->()->shortname;
92     }
93
94
95     my $depth;
96     if (defined($cgi->param('depth')) and not $query =~ /depth\(\d+\)/) {
97         $depth = defined $cgi->param('depth') ?
98             $cgi->param('depth') : $ctx->{get_aou}->($site)->ou_type->depth;
99         $query .= " depth($depth)";
100     }
101
102     return ($query, $site, $depth);
103 }
104
105 sub _get_search_limit {
106     my $self = shift;
107
108     # param takes precedence
109     my $limit = $self->cgi->param('limit');
110     return $limit if $limit;
111
112     if($self->editor->requestor) {
113         # See if the user has a hit count preference
114         my $lset = $self->editor->search_actor_user_setting({
115             usr => $self->editor->requestor->id, 
116             name => 'opac.hits_per_page'
117         })->[0];
118         return OpenSRF::Utils::JSON->JSON2perl($lset->value) if $lset;
119     }
120
121     return 10; # default
122 }
123
124 # context additions: 
125 #   page_size
126 #   hit_count
127 #   records : list of bre's and copy-count objects
128 sub load_rresults {
129     my $self = shift;
130     my $cgi = $self->cgi;
131     my $ctx = $self->ctx;
132     my $e = $self->editor;
133
134     $ctx->{page} = 'rresult';
135
136     if ($cgi->param("_special")) {
137         return $self->marc_expert_search if scalar($cgi->param("tag"));
138         return $self->item_barcode_shortcut if (
139             $cgi->param("qtype") and ($cgi->param("qtype") eq "item_barcode")
140         );
141         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
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             if (defined $U->event_code($rec_ids)) {
239                 $self->apache->log->warn(
240                     "$method returned event: " . $U->event_code($rec_ids)
241                 );
242             } else {
243                 $self->apache->log->warn(
244                     "$method returned something unexpected: $rec_ids"
245                 );
246             }
247             return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
248         }
249
250         my ($facets, @data) = $self->get_records_and_facets(
251             $rec_ids, undef, {flesh => "{holdings_xml,mra}"}
252         );
253
254         $self->ctx->{records} = [@data];
255         $self->ctx->{search_facets} = {};
256         $self->ctx->{hit_count} = scalar @data;
257         $self->ctx->{page_size} = $self->ctx->{hit_count};
258
259         return Apache2::Const::OK;
260     } {
261         $self->apache->log->warn("couldn't connect to open-ils.search");
262         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
263     }
264 }
265
266 # like item_barcode_search, this can't take all the usual search params, but
267 # this one will at least do site, limit and page
268 sub marc_expert_search {
269     my ($self) = @_;
270
271     my @tags = $self->cgi->param("tag");
272     my @subfields = $self->cgi->param("subfield");
273     my @terms = $self->cgi->param("term");
274
275     my $query = [];
276     for (my $i = 0; $i < scalar @tags; $i++) {
277         push @$query, {
278             "term" => $terms[$i],
279             "restrict" => [{"tag" => $tags[$i], "subfield" => $subfields[$i]}]
280         };
281     }
282
283     # loc, limit and offset
284     my $page = $self->cgi->param("page") || 0;
285     my $limit = $self->_get_search_limit;
286     my $org_unit = $self->cgi->param("loc") || $self->ctx->{aou_tree}->()->id;
287     my $offset = $page * $limit;
288
289     if (my $search = create OpenSRF::AppSession("open-ils.search")) {
290         my $results = $search->request(
291             "open-ils.search.biblio.marc", {
292                 "searches" => $query, "org_unit" => $org_unit
293             }, $limit, $offset
294         )->gather(1);
295
296         if (defined $U->event_code($results)) {
297             $self->apache->log->warn(
298                 "open-ils.search.biblio.marc returned event: " .
299                 $U->event_code($results)
300             );
301             return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
302         }
303
304         my ($facets, @data) = $self->get_records_and_facets(
305             # filter out nulls that will turn up here
306             [ grep { $_ } @{$results->{ids}} ],
307             undef, {flesh => "{holdings_xml,mra}"}
308         );
309
310         $self->ctx->{records} = [@data];
311         $self->ctx->{search_facets} = {};
312
313         $self->ctx->{page_size} = $limit;
314         $self->ctx->{hit_count} = $results->{count};
315
316         return Apache2::Const::OK;
317     } else {
318         $self->apache->log->warn("couldn't connect to open-ils.search");
319         return Apache2::Const::HTTP_INTERNAL_SERVER_ERROR;
320     }
321 }
322
323 1;