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