e2ea613a37781d1403b568c352036942cfb89e56
[evergreen-equinox.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 my $U = 'OpenILS::Application::AppUtils';
9
10
11 sub _prepare_biblio_search_basics {
12     my ($cgi) = @_;
13
14     return $cgi->param('query') unless $cgi->param('qtype');
15
16     my %parts;
17     my @part_names = qw/qtype contains query/;
18     $parts{$_} = [ $cgi->param($_) ] for (@part_names);
19
20     my @chunks = ();
21     for (my $i = 0; $i < scalar @{$parts{'qtype'}}; $i++) {
22         my ($qtype, $contains, $query) = map { $parts{$_}->[$i] } @part_names;
23
24         next unless $query =~ /\S/;
25         push(@chunks, $qtype . ':') unless $qtype eq 'keyword' and $i == 0;
26
27         # This stuff probably will need refined or rethought to better handle
28         # the weird things Real Users will surely type in.
29         if ($contains eq 'nocontains') {
30             $query =~ s/"//g;
31             $query = ('"' . $query . '"') if index $query, ' ';
32             $query = '-' . $query;
33         } elsif ($contains eq 'phrase') {
34             $query =~ s/"//g;
35             $query = ('"' . $query . '"') if index $query, ' ';
36         } elsif ($contains eq 'exact') {
37             $query =~ s/[\^\$]//g;
38             $query = '^' . $query . '$';
39         }
40         push @chunks, $query;
41     }
42
43     return join(' ', @chunks);
44 }
45
46 sub _prepare_biblio_search {
47     my ($cgi, $ctx) = @_;
48
49     my $query = _prepare_biblio_search_basics($cgi);
50
51     $query = ('#' . $_ . ' ' . $query) foreach ($cgi->param('modifier'));
52
53     foreach (grep /^fi:/, $cgi->param) {
54         /:(\w+)$/ or next;
55         my $term = join(",", $cgi->param($_));
56         $query .= " $1($term)" if length $term;
57     }
58
59     if ($cgi->param('sort')) {
60         my ($axis, $desc) = split /\./, $cgi->param('sort');
61         $query .= " sort($axis)";
62         $query .= '#descending' if $desc;
63     }
64
65     if ($cgi->param('pubdate') && $cgi->param('date1')) {
66         if ($cgi->param('pubdate') eq 'between') {
67             $query .= ' between(' . $cgi->param('date1');
68             $query .= ',' .  $cgi->param('date2') if $cgi->param('date2');
69             $query .= ')';
70         } elsif ($cgi->param('pubdate') eq 'is') {
71             $query .= ' between(' . $cgi->param('date1') .
72                 ',' .  $cgi->param('date1') . ')';  # sic, date1 twice
73         } else {
74             $query .= ' ' . $cgi->param('pubdate') .
75                 '(' . $cgi->param('date1') . ')';
76         }
77     }
78
79     my $site = $cgi->param('loc') || $ctx->{aou_tree}->()->id;
80     if (defined($cgi->param('loc')) or not $query =~ /site\(\d+\)/) {
81         $query .= " site($site)";
82     }
83     if (defined($cgi->param('depth')) or not $query =~ /depth\(\d+\)/) {
84         my $depth = defined $cgi->param('depth') ?
85             $cgi->param('depth') : $ctx->{find_aou}->($site)->ou_type->depth;
86         $query .= " depth($depth)";
87     }
88
89     return $query;
90 }
91
92 # context additions: 
93 #   page_size
94 #   hit_count
95 #   records : list of bre's and copy-count objects
96 sub load_rresults {
97     my $self = shift;
98     my $cgi = $self->cgi;
99     my $ctx = $self->ctx;
100     my $e = $self->editor;
101
102     $ctx->{page} = 'rresult';
103     my $page = $cgi->param('page') || 0;
104     my $facet = $cgi->param('facet');
105     my $limit = $cgi->param('limit') || 10; # TODO user settings
106     my $offset = $page * $limit;
107
108     my $query = _prepare_biblio_search($cgi, $ctx);
109     # Limit and offset will stay here. Everything else should be part of
110     # the query string, not special args.
111     my $args = {'limit' => $limit, 'offset' => $offset};
112
113     # Stuff these into the TT context so that templates can use them in redrawing forms
114     $ctx->{processed_search_query} = $query;
115
116     $query = "$query $facet" if $facet; # TODO
117
118     my $results;
119
120     try {
121
122         my $method = 'open-ils.search.biblio.multiclass.query';
123         $method .= '.staff' if $ctx->{is_staff};
124         $results = $U->simplereq('open-ils.search', $method, $args, $query, 1);
125
126     } catch Error with {
127         my $err = shift;
128         $logger->error("multiclass search error: $err");
129         $results = {count => 0, ids => []};
130     };
131
132     my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
133
134     $ctx->{records} = [];
135     $ctx->{search_facets} = {};
136     $ctx->{page_size} = $limit;
137     $ctx->{hit_count} = $results->{count};
138
139     return Apache2::Const::OK if @$rec_ids == 0;
140
141     my $cstore1 = OpenSRF::AppSession->create('open-ils.cstore');
142     my $bre_req = $cstore1->request(
143         'open-ils.cstore.direct.biblio.record_entry.search', {id => $rec_ids});
144
145     my $search = OpenSRF::AppSession->create('open-ils.search');
146     my $facet_req = $search->request('open-ils.search.facet_cache.retrieve', $results->{facet_key}, 10);
147
148     my @data;
149     while(my $resp = $bre_req->recv) {
150         my $bre = $resp->content; 
151
152         # XXX farm out to multiple cstore sessions before loop, then collect after
153         my $copy_counts = $e->json_query(
154             {from => ['asset.record_copy_count', 1, $bre->id, 0]})->[0];
155
156         push(@data,
157             {
158                 bre => $bre,
159                 marc_xml => XML::LibXML->new->parse_string($bre->marc),
160                 copy_counts => $copy_counts
161             }
162         );
163     }
164
165     $cstore1->kill_me;
166
167     # shove recs into context in search results order
168     for my $rec_id (@$rec_ids) { 
169         push(
170             @{$ctx->{records}},
171             grep { $_->{bre}->id == $rec_id } @data
172         );
173     }
174
175     my $facets = $facet_req->gather(1);
176
177     $facets->{$_} = {cmf => $ctx->{find_cmf}->($_), data => $facets->{$_}} for keys %$facets;  # quick-n-dirty
178     $ctx->{search_facets} = $facets;
179
180     return Apache2::Const::OK;
181 }
182
183 1;