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