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