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