]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader/Record.pm
TPAC advanced search org unit selector
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGCatLoader / Record.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 Net::HTTP::NB;
9 use IO::Select;
10 my $U = 'OpenILS::Application::AppUtils';
11
12 our $ac_types = ['toc',  'anotes', 'excerpt', 'summary', 'reviews'];
13
14 # context additions: 
15 #   record : bre object
16 sub load_record {
17     my $self = shift;
18     my $ctx = $self->ctx;
19     $ctx->{page} = 'record';  
20
21     $self->timelog("load_record() began");
22
23     my $rec_id = $ctx->{page_args}->[0]
24         or return Apache2::Const::HTTP_BAD_REQUEST;
25
26     $self->added_content_stage1($rec_id);
27     $self->timelog("past added content stage 1");
28
29     my $org = $self->_get_search_lib();
30     my $org_name = $ctx->{get_aou}->($org)->shortname;
31     my $pref_ou = $self->_get_pref_lib();
32     my $depth = $self->cgi->param('depth');
33     $depth = $ctx->{get_aou}->($org)->ou_type->depth 
34         unless defined $depth; # can be 0
35
36     my $copy_depth = $self->cgi->param('copy_depth');
37     $copy_depth = $depth unless defined $copy_depth; # can be 0
38     $self->ctx->{copy_depth} = $copy_depth;
39
40     my $copy_limit = int($self->cgi->param('copy_limit') || 10);
41     my $copy_offset = int($self->cgi->param('copy_offset') || 0);
42
43     $self->get_staff_search_settings;
44     if ($ctx->{staff_saved_search_size}) {
45         $ctx->{saved_searches} = ($self->staff_load_searches)[1];
46     }
47     $self->timelog("past staff saved searches");
48
49     $self->fetch_related_search_info($rec_id);
50     $self->timelog("past related search info");
51
52     # Check for user and load lists and prefs
53     if ($self->ctx->{user}) {
54         $self->_load_lists_and_settings;
55         $self->timelog("load user lists and settings");
56     }
57
58     # run copy retrieval in parallel to bib retrieval
59     # XXX unapi
60     my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
61     my $copy_rec = $cstore->request(
62         'open-ils.cstore.json_query.atomic', 
63         $self->mk_copy_query($rec_id, $org, $copy_depth, $copy_limit, $copy_offset, $pref_ou)
64     );
65
66     my (undef, @rec_data) = $self->get_records_and_facets([$rec_id], undef, {
67         flesh => '{holdings_xml,bmp,mra,acp,acnp,acns}',
68         site => $org_name,
69         depth => $depth,
70         pref_lib => $pref_ou
71     });
72
73     $self->timelog("past get_records_and_facets()");
74     $ctx->{bre_id} = $rec_data[0]->{id};
75     $ctx->{marc_xml} = $rec_data[0]->{marc_xml};
76
77     $ctx->{copies} = $copy_rec->gather(1);
78     $self->timelog("past store copy retrieval call");
79     $ctx->{copy_limit} = $copy_limit;
80     $ctx->{copy_offset} = $copy_offset;
81
82     $ctx->{have_holdings_to_show} = 0;
83     $ctx->{have_mfhd_to_show} = 0;
84
85     $self->get_hold_copy_summary($rec_id, $org);
86
87     $self->timelog("past get_hold_copy_summary()");
88     $self->ctx->{bib_is_dead} = OpenILS::Application::AppUtils->is_true(
89         OpenILS::Utils::CStoreEditor->new->json_query({
90             select => { bre => [ 'deleted' ] },
91             from => 'bre',
92             where => { 'id' => $rec_id }
93         })->[0]->{deleted}
94     );
95
96     $cstore->kill_me;
97
98     if (
99         $ctx->{get_org_setting}->
100             ($org, "opac.fully_compressed_serial_holdings")
101     ) {
102         # We're loading this data here? Are we therefore assuming that we
103         # *are* going to display something in the "issues" expandy?
104         $self->load_serial_holding_summaries($rec_id, $org, $copy_depth);
105     } else {
106         $ctx->{mfhd_summaries} =
107             $self->get_mfhd_summaries($rec_id, $org, $copy_depth);
108
109         if ($ctx->{mfhd_summaries} && scalar(@{$ctx->{mfhd_summaries}})
110         ) {
111             $ctx->{have_mfhd_to_show} = 1;
112         };
113     }
114
115     $self->timelog("past serials holding stuff");
116
117     my %expandies = (
118         marchtml => sub {
119             $ctx->{marchtml} = $self->mk_marc_html($rec_id);
120         },
121         issues => sub {
122             return;
123             # XXX this needed?
124         },
125         cnbrowse => sub {
126             $self->prepare_browse_call_numbers();
127         }
128     );
129
130     my @expand = $self->cgi->param('expand');
131     if (grep {$_ eq 'all'} @expand) {
132         $ctx->{expand_all} = 1;
133         $expandies{$_}->() for keys %expandies;
134
135     } else {
136         for my $exp (@expand) {
137             $ctx->{"expand_$exp"} = 1;
138             $expandies{$exp}->() if exists $expandies{$exp};
139         }
140     }
141
142     $self->timelog("past expandies");
143
144     $self->added_content_stage2($rec_id);
145
146     $self->timelog("past added content stage 2");
147
148     return Apache2::Const::OK;
149 }
150
151 # collect IDs and info on the search that lead to this details page
152 # If no search query, etc is present, we leave ctx.search_result_index == -1
153 sub fetch_related_search_info {
154     my $self = shift;
155     my $rec_id = shift;
156     my $ctx = $self->ctx;
157     $ctx->{search_result_index} = -1;
158
159     $self->load_rresults(internal => 1);
160
161     my @search_ids = @{$ctx->{ids}};
162     return unless @search_ids;
163
164     for my $idx (0..$#search_ids) {
165         if ($search_ids[$idx] == $rec_id) {
166             $ctx->{prev_search_record} = $search_ids[$idx - 1] if $idx > 0;
167             $ctx->{next_search_record} = $search_ids[$idx + 1];
168             $ctx->{search_result_index} = $idx;
169             last;
170         }
171     }
172
173     $ctx->{first_search_record} = $search_ids[0];
174     $ctx->{last_search_record} = $search_ids[-1];
175 }
176
177
178 sub mk_copy_query {
179     my $self = shift;
180     my $rec_id = shift;
181     my $org = shift;
182     my $depth = shift;
183     my $copy_limit = shift;
184     my $copy_offset = shift;
185     my $pref_ou = shift;
186
187     my $query = $U->basic_opac_copy_query(
188         $rec_id, undef, undef, $copy_limit, $copy_offset, $self->ctx->{is_staff}
189     );
190
191     if($org != $self->ctx->{aou_tree}->()->id) { 
192         # no need to add the org join filter if we're not actually filtering
193         $query->{from}->{acp}->{aou} = {
194             fkey => 'circ_lib',
195             field => 'id',
196             filter => {
197                 id => {
198                     in => {
199                         select => {aou => [{
200                             column => 'id', 
201                             transform => 'actor.org_unit_descendants',
202                             result_field => 'id', 
203                             params => [$depth]
204                         }]},
205                         from => 'aou',
206                         where => {id => $org}
207                     }
208                 }
209             }
210         };
211     };
212
213     # Unsure if we want these in the shared function, leaving here for now
214     unshift(@{$query->{order_by}},
215         { class => "aou", field => 'id',
216           transform => 'evergreen.rank_ou', params => [$org, $pref_ou]
217         }
218     );
219     push(@{$query->{order_by}},
220         { class => "acp", field => 'status',
221           transform => 'evergreen.rank_cp_status'
222         }
223     );
224
225     return $query;
226 }
227
228 sub mk_marc_html {
229     my($self, $rec_id) = @_;
230
231     # could be optimized considerably by performing the xslt on the already fetched record
232     return $U->simplereq(
233         'open-ils.search', 
234         'open-ils.search.biblio.record.html', $rec_id, 1);
235 }
236
237 sub load_serial_holding_summaries {
238     my ($self, $rec_id, $org, $depth) = @_;
239
240     my $limit = $self->cgi->param("slimit") || 10;
241     my $offset = $self->cgi->param("soffset") || 0;
242
243     my $serial = create OpenSRF::AppSession("open-ils.serial");
244
245     # First, get the tree of /summaries/ of holdings.
246     my $tree = $serial->request(
247         "open-ils.serial.holding_summary_tree.by_bib",
248         $rec_id, $org, $depth, $limit, $offset
249     )->gather(1);
250
251     return if $self->apache_log_if_event(
252         $tree, "getting holding summary tree for record $rec_id"
253     );
254
255     # Next, if requested, get a list of individual holdings under a
256     # particular summary.
257     my $holdings;
258     my $summary_id = int($self->cgi->param("sid") || 0);
259     my $summary_type = $self->cgi->param("stype");
260
261     if ($summary_id and $summary_type) {
262         my $expand_path = [ $self->cgi->param("sepath") ],
263         my $expand_limit = $self->cgi->param("selimit");
264         my $expand_offsets = [ $self->cgi->param("seoffset") ];
265         my $auto_expand_first = 0;
266
267         if (not @$expand_offsets) {
268             $expand_offsets = undef;
269             $auto_expand_first = 1;
270         }
271
272         $holdings = $serial->request(
273             "open-ils.serial.holdings.grouped_by_summary",
274             $summary_type, $summary_id,
275             $expand_path, $expand_limit, $expand_offsets,
276             $auto_expand_first,
277             1 + ($self->ctx->{is_staff} ? 1 : 0)
278         )->gather(1);
279
280         if ($holdings and ref $holdings eq "ARRAY") {
281             $self->place_holdings_with_summary(
282                     $tree, $holdings, $summary_id, $summary_type
283             ) or $self->apache->log->warn(
284                 "could not place holdings within summary tree"
285             );
286         } else {
287             $self->apache_log_if_event(
288                 $holdings, "getting holdings grouped by summary $summary_id"
289             );
290         }
291     }
292
293     $serial->kill_me;
294
295     # The presence of any keys in the tree hash other than 'more' means that we
296     # must have /something/ we could show.
297     $self->ctx->{have_holdings_to_show} = grep { $_ ne 'more' } (keys %$tree);
298
299     $self->ctx->{holding_summary_tree} = $tree;
300 }
301
302 # This helper to load_serial_holding_summaries() recursively searches in
303 # $tree for a holding summary matching $sid and $stype, and places $holdings
304 # within the node for that summary. IOW, this is about showing expanded
305 # holdings under their "parent" summary.
306 sub place_holdings_with_summary {
307     my ($self, $tree, $holdings, $sid, $stype) = @_;
308
309     foreach my $sum (@{$tree->{holding_summaries}}) {
310         if ($sum->{id} == $sid and $sum->{summary_type} eq $stype) {
311             $sum->{holdings} = $holdings;
312             return 1;
313         }
314     }
315
316     foreach my $child (@{$tree->{children}}) {
317         return 1 if $self->place_holdings_with_summary(
318             $child, $holdings, $sid, $stype
319         );
320     }
321
322     return;
323 }
324
325 sub get_mfhd_summaries {
326     my ($self, $rec_id, $org, $depth) = @_;
327
328     my $serial = create OpenSRF::AppSession("open-ils.search");
329     my $result = $serial->request(
330         "open-ils.search.serial.record.bib.retrieve",
331         $rec_id, $org, $depth
332     )->gather(1);
333
334     $serial->kill_me;
335     return $result;
336 }
337
338 sub any_call_number_label {
339     my ($self) = @_;
340
341     if ($self->ctx->{copies} and @{$self->ctx->{copies}}) {
342         return $self->ctx->{copies}->[0]->{call_number_label};
343     } else {
344         return;
345     }
346 }
347
348 sub prepare_browse_call_numbers {
349     my ($self) = @_;
350
351     my $cn = ($self->cgi->param("cn") || $self->any_call_number_label) or
352         return [];
353
354     my $org_unit = $self->ctx->{get_aou}->($self->cgi->param('loc')) ||
355         $self->ctx->{aou_tree}->();
356
357     my $supercat = create OpenSRF::AppSession("open-ils.supercat");
358     my $results = $supercat->request(
359         "open-ils.supercat.call_number.browse", 
360         $cn, $org_unit->shortname, 9, $self->cgi->param("cnoffset")
361     )->gather(1) || [];
362
363     $supercat->kill_me;
364
365     $self->ctx->{browsed_call_numbers} = [
366         map {
367             $_->record->marc(
368                 (new XML::LibXML)->parse_string($_->record->marc)
369             );
370             $_;
371         } @$results
372     ];
373     $self->ctx->{browsing_ou} = $org_unit;
374 }
375
376 sub get_hold_copy_summary {
377     my ($self, $rec_id, $org) = @_;
378     
379     my $search = OpenSRF::AppSession->create('open-ils.search');
380     my $req1 = $search->request(
381         'open-ils.search.biblio.record.copy_count', $org, $rec_id); 
382
383     $self->ctx->{record_hold_count} = $U->simplereq(
384         'open-ils.circ', 'open-ils.circ.bre.holds.count', $rec_id);
385
386     $self->ctx->{copy_summary} = $req1->recv->content;
387
388     $search->kill_me;
389 }
390
391 sub load_print_record {
392     my $self = shift;
393
394     my $rec_id = $self->ctx->{page_args}->[0] 
395         or return Apache2::Const::HTTP_BAD_REQUEST;
396
397     $self->{ctx}->{bre_id} = $rec_id;
398     $self->{ctx}->{printable_record} = $U->simplereq(
399         'open-ils.search',
400         'open-ils.search.biblio.record.print', $rec_id);
401
402     return Apache2::Const::OK;
403 }
404
405 sub load_email_record {
406     my $self = shift;
407
408     my $rec_id = $self->ctx->{page_args}->[0] 
409         or return Apache2::Const::HTTP_BAD_REQUEST;
410
411     $self->{ctx}->{bre_id} = $rec_id;
412     $U->simplereq(
413         'open-ils.search',
414         'open-ils.search.biblio.record.email', 
415         $self->ctx->{authtoken}, $rec_id);
416
417     return Apache2::Const::OK;
418 }
419
420 # for each type, fire off the reqeust to see if content is available
421 # ctx.added_content.$type.status:
422 #   1 == available
423 #   2 == not available
424 #   3 == unknown
425 sub added_content_stage1 {
426     my $self = shift;
427     my $rec_id = shift;
428     my $ctx = $self->ctx;
429     my $sel_type = $self->cgi->param('ac') || '';
430     my $key = $self->get_ac_key($rec_id);
431     ($key = $key->{value}) =~ s/^\s+//g if $key;
432
433     $ctx->{added_content} = {};
434     for my $type (@$ac_types) {
435         $ctx->{added_content}->{$type} = {content => ''};
436         $ctx->{added_content}->{$type}->{status} = $key ? 3 : 2;
437
438         if ($key) {
439             $logger->debug("tpac: starting added content request for $key => $type");
440
441             my $req = Net::HTTP::NB->new(Host => $self->apache->hostname);
442
443             if (!$req) {
444                 $logger->warn("Unable to fetch added content from " . $self->apache->hostname . ": $@");
445                 next;
446             }
447
448             my $http_type = ($type eq $sel_type) ? 'GET' : 'HEAD';
449             $req->write_request($http_type => "/opac/extras/ac/$type/html/" . uri_escape($key));
450             $ctx->{added_content}->{$type}->{request} = $req;
451         }
452     }
453 }
454
455 # check each outstanding request.  If it's ready, read the HTTP 
456 # status and use it to determine if content is available.  Otherwise,
457 # leave the status as unknown.
458 sub added_content_stage2 {
459     my $self = shift;
460     my $ctx = $self->ctx;
461     my $sel_type = $self->cgi->param('ac') || '';
462
463     for my $type (keys %{$ctx->{added_content}}) {
464         my $content = $ctx->{added_content}->{$type};
465
466         if ($content->{status} == 3) {
467             $logger->debug("tpac: finishing added content request for $type");
468
469             my $req = $content->{request};
470             my $sel = IO::Select->new($req);
471
472             # if we are requesting a specific type of content, give the 
473             # backend code a little extra time to retrieve the content.
474             my $wait = $type eq $sel_type ? 3 : 0; # TODO: config?
475
476             if ($sel->can_read($wait)) {
477                 my ($code) = $req->read_response_headers;
478                 $content->{status} = $code eq '200' ? 1 : 2;
479                 $logger->debug("tpac: added content request for $type returned $code");
480
481                 if ($code eq '200' and $type eq $sel_type) {
482                     while (1) {
483                         my $buf;
484                         my $n = $req->read_entity_body($buf, 1024);
485                         last unless $n;
486                         $content->{content} .= $buf;
487                     }
488                 }
489             }
490         }
491     }
492 }
493
494 # XXX this is copied directly from AddedContent.pm in 
495 # working/user/jeff/ac_by_record_id_rebase.  When Jeff's
496 # branch is merged and Evergreen gets added content 
497 # lookup by ID, this can be removed.
498 # returns [{tag => $tag, value => $value}, {tag => $tag2, value => $value2}]
499 sub get_ac_key {
500     my $self = shift;
501     my $rec_id = shift;
502     my $key_data = $self->editor->json_query({
503         select => {mfr => ['tag', 'value']},
504         from => 'mfr',
505         where => {
506             record => $rec_id,
507             '-or' => [
508                 {
509                     '-and' => [
510                         {tag => '020'},
511                         {subfield => 'a'}
512                     ]
513                 }, {
514                     '-and' => [
515                         {tag => '024'},
516                         {subfield => 'a'},
517                         {ind1 => 1}
518                     ]
519                 }
520             ]
521         }
522     });
523
524     return (
525         grep {$_->{tag} eq '020'} @$key_data,
526         grep {$_->{tag} eq '024'} @$key_data
527     )[0];
528 }
529
530 1;