1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
5 use Digest::MD5 qw(md5_hex);
6 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
7 use OpenSRF::AppSession;
8 use OpenSRF::EX qw/:try/;
9 use OpenSRF::Utils qw/:datetime/;
10 use OpenSRF::Utils::JSON;
11 use OpenSRF::Utils::Logger qw/$logger/;
12 use OpenILS::Application::AppUtils;
13 use OpenILS::Utils::CStoreEditor qw/:funcs/;
14 use OpenILS::Utils::Fieldmapper;
15 use DateTime::Format::ISO8601;
16 my $U = 'OpenILS::Application::AppUtils';
18 my %cache; # proc-level cache
21 my($class, $apache, $ctx) = @_;
23 my $self = bless({}, ref($class) || $class);
25 $self->apache($apache);
29 OpenILS::Utils::CStoreEditor->init; # just in case
30 $self->editor(new_editor());
36 # current Apache2::RequestRec;
38 my($self, $apache) = @_;
39 $self->{apache} = $apache if $apache;
40 return $self->{apache};
43 # runtime / template context
46 $self->{ctx} = $ctx if $ctx;
52 my($self, $editor) = @_;
53 $self->{editor} = $editor if $editor;
54 return $self->{editor};
60 $self->{cgi} = $cgi if $cgi;
65 # load common data, then load page data
70 my $stat = $self->load_common;
71 return $stat unless $stat == Apache2::Const::OK;
73 my $path = $self->apache->path_info;
75 return $self->load_home if $path =~ /opac\/home/;
76 return $self->load_login if $path =~ /opac\/login/;
77 return $self->load_logout if $path =~ /opac\/logout/;
78 return $self->load_rresults if $path =~ /opac\/results/;
79 return $self->load_record if $path =~ /opac\/record/;
81 # ----------------------------------------------------------------
82 # These pages require authentication
83 # ----------------------------------------------------------------
84 return Apache2::Const::FORBIDDEN unless $self->cgi->https;
85 return $self->load_logout unless $self->editor->requestor;
87 return $self->load_place_hold if $path =~ /opac\/place_hold/;
88 return $self->load_myopac_holds if $path =~ /opac\/myopac\/holds/;
89 return $self->load_myopac_circs if $path =~ /opac\/myopac\/circs/;
90 return $self->load_myopac_fines if $path =~ /opac\/myopac\/fines/;
91 return $self->load_myopac if $path =~ /opac\/myopac/;
92 # ----------------------------------------------------------------
94 return Apache2::Const::OK;
97 # general purpose utility functions added to the environment
100 my $e = $self->editor;
101 my $ctx = $self->ctx;
103 $cache{map} = {}; # public object maps
104 $cache{list} = {}; # public object lists
106 # fetch-on-demand-and-cache subs for commonly used public data
107 my @public_classes = qw/ccs aout/;
109 for my $hint (@public_classes) {
112 $Fieldmapper::fieldmap->{$_}->{hint} eq $hint
113 } keys %{ $Fieldmapper::fieldmap };
115 $class =~ s/Fieldmapper:://o;
119 my $list_key = $hint . '_list';
120 my $find_key = "find_$hint";
122 $ctx->{$list_key} = sub {
123 my $method = "retrieve_all_$class";
124 $cache{list}{$hint} = $e->$method() unless $cache{list}{$hint};
125 return $cache{list}{$hint};
128 $cache{map}{$hint} = {};
130 $ctx->{$find_key} = sub {
132 return $cache{map}{$hint}{$id} if $cache{map}{$hint}{$id};
133 ($cache{map}{$hint}{$id}) = grep { $_->id == $id } @{$ctx->{$list_key}->()};
134 return $cache{map}{$hint}{$id};
139 $ctx->{aou_tree} = sub {
141 # fetch the org unit tree
142 unless($cache{aou_tree}) {
143 my $tree = $e->search_actor_org_unit([
144 { parent_ou => undef},
146 flesh_fields => {aou => ['children']},
147 order_by => {aou => 'name'}
151 # flesh the org unit type for each org unit
152 # and simultaneously set the id => aou map cache
156 $node->ou_type( $ctx->{find_aout}->($node->ou_type) );
157 $cache{map}{aou}{$node->id} = $node;
158 flesh_aout($_, $ctx) foreach @{$node->children};
160 flesh_aout($tree, $ctx);
162 $cache{aou_tree} = $tree;
165 return $cache{aou_tree};
168 # Add a special handler for the tree-shaped org unit cache
169 $cache{map}{aou} = {};
170 $ctx->{find_aou} = sub {
172 $ctx->{aou_tree}->(); # force the org tree to load
173 return $cache{map}{aou}{$org_id};
176 # turns an ISO date into something TT can understand
177 $ctx->{parse_datetime} = sub {
179 $date = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($date));
181 "%0.2d:%0.2d:%0.2d %0.2d-%0.2d-%0.4d",
195 # user_status : hash of user circ numbers
199 my $e = $self->editor;
200 my $ctx = $self->ctx;
202 if($e->authtoken($self->cgi->cookie('ses'))) {
206 $ctx->{authtoken} = $e->authtoken;
207 $ctx->{user} = $e->requestor;
208 $ctx->{user_stats} = $U->simplereq(
210 'open-ils.actor.user.opac.vital_stats',
211 $e->authtoken, $e->requestor->id);
215 return $self->load_logout;
219 return Apache2::Const::OK;
224 $self->ctx->{page} = 'home';
225 return Apache2::Const::OK;
231 my $cgi = $self->cgi;
233 $self->ctx->{page} = 'login';
235 my $username = $cgi->param('username');
236 my $password = $cgi->param('password');
238 return Apache2::Const::OK unless $username and $password;
240 my $seed = $U->simplereq(
242 'open-ils.auth.authenticate.init',
245 my $response = $U->simplereq(
247 'open-ils.auth.authenticate.complete',
248 { username => $username,
249 password => md5_hex($seed . md5_hex($password)),
254 # XXX check event, redirect as necessary
256 my $home = $self->apache->unparsed_uri;
257 $home =~ s/\/login/\/home/;
259 $self->apache->print(
261 -url => $cgi->param('origin') || $home,
262 -cookie => $cgi->cookie(
266 -value => $response->{payload}->{authtoken},
267 -expires => CORE::time + $response->{payload}->{authtime}
272 return Apache2::Const::REDIRECT;
278 my $url = 'http://' . $self->apache->hostname . $self->ctx->{base_path} . "/opac/home";
280 $self->apache->print(
281 $self->cgi->redirect(
283 -cookie => $self->cgi->cookie(
292 return Apache2::Const::REDIRECT;
298 # records : list of bre's and copy-count objects
301 my $cgi = $self->cgi;
302 my $ctx = $self->ctx;
303 my $e = $self->editor;
305 $ctx->{page} = 'rresult';
306 my $page = $cgi->param('page') || 0;
307 my $facet = $cgi->param('facet');
308 my $query = $cgi->param('query');
309 my $limit = $cgi->param('limit') || 10; # XXX user settings
310 my $args = {limit => $limit, offset => $page * $limit};
311 $query = "$query $facet" if $facet;
315 $results = $U->simplereq(
317 'open-ils.search.biblio.multiclass.query.staff',
322 $logger->error("multiclass search error: $err");
323 $results = {count => 0, ids => []};
326 my $rec_ids = [map { $_->[0] } @{$results->{ids}}];
328 $ctx->{records} = [];
329 $ctx->{search_facets} = {};
330 $ctx->{page_size} = $limit;
331 $ctx->{hit_count} = $results->{count};
333 return Apache2::Const::OK if @$rec_ids == 0;
335 my $cstore1 = OpenSRF::AppSession->create('open-ils.cstore');
336 my $bre_req = $cstore1->request(
337 'open-ils.cstore.direct.biblio.record_entry.search', {id => $rec_ids});
339 my $search = OpenSRF::AppSession->create('open-ils.search');
340 my $facet_req = $search->request('open-ils.search.facet_cache.retrieve', $results->{facet_key}, 10);
342 unless($cache{cmf}) {
343 $cache{cmf} = $e->search_config_metabib_field({id => {'!=' => undef}});
344 $ctx->{metabib_field} = $cache{cmf};
345 #$cache{cmc} = $e->search_config_metabib_class({name => {'!=' => undef}});
346 #$ctx->{metabib_class} = $cache{cmc};
350 while(my $resp = $bre_req->recv) {
351 my $bre = $resp->content;
353 # XXX farm out to multiple cstore sessions before loop, then collect after
354 my $copy_counts = $e->json_query(
355 {from => ['asset.record_copy_count', 1, $bre->id, 0]})->[0];
360 marc_xml => XML::LibXML->new->parse_string($bre->marc),
361 copy_counts => $copy_counts
368 # shove recs into context in search results order
369 for my $rec_id (@$rec_ids) {
372 grep { $_->{bre}->id == $rec_id } @data
376 my $facets = $facet_req->gather(1);
378 for my $cmf_id (keys %$facets) { # quick-n-dirty
379 my ($cmf) = grep { $_->id eq $cmf_id } @{$cache{cmf}};
380 $facets->{$cmf_id} = {cmf => $cmf, data => $facets->{$cmf_id}};
382 $ctx->{search_facets} = $facets;
384 return Apache2::Const::OK;
388 # record : bre object
391 $self->ctx->{page} = 'record';
393 my $rec_id = $self->ctx->{page_args}->[0]
394 or return Apache2::Const::HTTP_BAD_REQUEST;
396 $self->ctx->{record} = $self->editor->retrieve_biblio_record_entry([
401 bre => ['call_numbers'],
402 acn => ['copies'] # limit, paging, etc.
407 $self->ctx->{marc_xml} = XML::LibXML->new->parse_string($self->ctx->{record}->marc);
409 return Apache2::Const::OK;
413 # user : au object, fleshed
416 $self->ctx->{page} = 'myopac';
418 $self->ctx->{user} = $self->editor->retrieve_actor_user([
419 $self->ctx->{user}->id,
429 return Apache2::Const::OK;
432 sub load_myopac_holds {
434 my $e = $self->editor;
435 my $ctx = $self->ctx;
437 my $limit = $self->cgi->param('limit') || 0;
438 my $offset = $self->cgi->param('offset') || 0;
440 my $circ = OpenSRF::AppSession->create('open-ils.circ');
441 my $hold_ids = $circ->request(
442 'open-ils.circ.holds.id_list.retrieve',
447 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
449 my $req = $circ->request(
450 'open-ils.circ.hold.details.batch.retrieve',
454 suppress_notices => 1,
455 suppress_transits => 1,
457 suppress_patron_details => 1,
462 # any requests we can fire off here?
465 while(my $resp = $req->recv) {
466 my $hold = $resp->content;
467 push(@{$ctx->{holds}}, {
469 marc_xml => XML::LibXML->new->parse_string($hold->{bre}->marc)
474 return Apache2::Const::OK;
477 sub load_place_hold {
479 my $ctx = $self->ctx;
480 my $e = $self->editor;
481 $self->ctx->{page} = 'place_hold';
483 $ctx->{hold_target} = $self->cgi->param('hold_target');
484 $ctx->{hold_type} = $self->cgi->param('hold_type');
485 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # XXX staff
487 if($ctx->{hold_type} eq 'T') {
488 $ctx->{record} = $e->retrieve_biblio_record_entry($ctx->{hold_target});
492 $ctx->{marc_xml} = XML::LibXML->new->parse_string($ctx->{record}->marc);
494 if(my $pickup_lib = $self->cgi->param('pickup_lib')) {
497 patronid => $e->requestor->id,
498 titleid => $ctx->{hold_target}, # XXX
499 pickup_lib => $pickup_lib,
503 my $allowed = $U->simplereq(
505 'open-ils.circ.title_hold.is_possible',
509 if($allowed->{success} == 1) {
510 my $hold = Fieldmapper::action::hold_request->new;
512 $hold->pickup_lib($pickup_lib);
513 $hold->requestor($e->requestor->id);
514 $hold->usr($e->requestor->id); # XXX staff
515 $hold->target($ctx->{hold_target});
516 $hold->hold_type($ctx->{hold_type});
517 # frozen, expired, etc..
519 my $stat = $U->simplereq(
521 'open-ils.circ.holds.create',
525 if($stat and $stat > 0) {
526 $ctx->{hold_success} = 1;
528 $ctx->{hold_failed} = 1; # XXX process the events, etc
532 # place the hold and deliver results
535 return Apache2::Const::OK;
539 sub fetch_user_circs {
541 my $flesh = shift; # flesh bib data, etc.
542 my $circ_ids = shift;
546 my $e = $self->editor;
551 @circ_ids = @$circ_ids;
555 my $circ_data = $U->simplereq(
557 'open-ils.actor.user.checked_out',
562 @circ_ids = ( @{$circ_data->{overdue}}, @{$circ_data->{out}} );
564 if($limit or $offset) {
565 @circ_ids = grep { defined $_ } @circ_ids[0..($offset + $limit - 1)];
569 return [] unless @circ_ids;
571 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
576 circ => ['target_copy'],
577 acp => ['call_number'],
583 my $circs = $e->search_action_circulation(
584 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
587 for my $circ (@$circs) {
590 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
591 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
592 undef # pre-cat copy, use the dummy title/author instead
597 # make sure the final list is in the correct order
599 for my $id (@circ_ids) {
602 (grep { $_->{circ}->id == $id } @circs)
606 return \@sorted_circs;
610 sub handle_circ_renew {
613 my $ctx = $self->ctx;
615 my @renew_ids = $self->cgi->param('circ');
617 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
619 # TODO: fire off renewal calls in batches to speed things up
621 for my $circ (@$circs) {
623 my $evt = $U->simplereq(
625 'open-ils.circ.renew',
626 $self->editor->authtoken,
628 patron_id => $self->editor->requestor->id,
629 copy_id => $circ->{circ}->target_copy,
634 # TODO return these, then insert them into the circ data
635 # blob that is shoved into the template for each circ
636 # so the template won't have to match them
637 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
644 sub load_myopac_circs {
646 my $e = $self->editor;
647 my $ctx = $self->ctx;
650 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
651 my $offset = $self->cgi->param('offset') || 0;
652 my $action = $self->cgi->param('action') || '';
654 # perform the renewal first if necessary
655 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
657 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
659 my $success_renewals = 0;
660 my $failed_renewals = 0;
661 for my $data (@{$ctx->{circs}}) {
662 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
665 #$self->apache->log->warn("renewal response: " . OpenSRF::Utils::JSON->perl2JSON($resp));
666 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
667 $data->{renewal_response} = $evt;
668 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
669 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
673 $ctx->{success_renewals} = $success_renewals;
674 $ctx->{failed_renewals} = $failed_renewals;
676 return Apache2::Const::OK;
679 sub load_myopac_fines {
681 my $e = $self->editor;
682 my $ctx = $self->ctx;
688 my $limit = $self->cgi->param('limit') || 0;
689 my $offset = $self->cgi->param('offset') || 0;
691 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
693 # TODO: This should really use a ML call, but the existing calls
694 # return an excessive amount of data and don't offer streaming
696 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
698 my $req = $cstore->request(
699 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
701 usr => $e->requestor->id,
702 balance_owed => {'!=' => 0}
707 mobts => ['circulation', 'grocery'],
710 circ => ['target_copy'],
711 acp => ['call_number'],
714 order_by => { mobts => 'xact_start' },
719 while(my $resp = $req->recv) {
720 my $mobts = $resp->content;
721 my $circ = $mobts->circulation;
724 if($mobts->grocery) {
725 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
726 $last_billing = pop(@billings);
730 @{$ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
733 last_grocery_billing => $last_billing,
734 marc_xml => ($mobts->xact_type ne 'circulation' or $circ->target_copy->call_number->id == -1) ?
736 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc),
741 return Apache2::Const::OK;