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;
433 sub fetch_user_holds {
435 my $hold_ids = shift;
436 my $ids_only = shift;
441 my $e = $self->editor;
443 my $circ = OpenSRF::AppSession->create('open-ils.circ');
447 $hold_ids = $circ->request(
448 'open-ils.circ.holds.id_list.retrieve.authoritative',
453 $hold_ids = [ grep { defined $_ } @$hold_ids[$offset..($offset + $limit - 1)] ] if $limit or $offset;
457 return $hold_ids if $ids_only or @$hold_ids == 0;
459 my $req = $circ->request(
460 # TODO .authoritative version is chewing up cstores
461 # 'open-ils.circ.hold.details.batch.retrieve.authoritative',
462 'open-ils.circ.hold.details.batch.retrieve',
466 suppress_notices => 1,
467 suppress_transits => 1,
469 suppress_patron_details => 1,
475 while(my $resp = $req->recv) {
476 my $hold = $resp->content;
479 marc_xml => ($flesh) ? XML::LibXML->new->parse_string($hold->{bre}->marc) : undef
487 sub handle_hold_update {
490 my $e = $self->editor;
493 my @hold_ids = $self->cgi->param('hold_id'); # for non-_all actions
494 @hold_ids = @{$self->fetch_user_holds(undef, 1)} if $action =~ /_all/;
496 my $circ = OpenSRF::AppSession->create('open-ils.circ');
498 if($action =~ /cancel/) {
500 for my $hold_id (@hold_ids) {
501 my $resp = $circ->request(
502 'open-ils.circ.hold.cancel', $e->authtoken, $hold_id, 6 )->gather(1); # 6 == patron-cancelled-via-opac
508 for my $hold_id (@hold_ids) {
509 my $vals = {id => $hold_id};
511 if($action =~ /activate/) {
512 $vals->{frozen} = 'f';
513 $vals->{thaw_date} = undef;
515 } elsif($action =~ /suspend/) {
516 $vals->{frozen} = 't';
517 # $vals->{thaw_date} = TODO;
519 push(@$vlist, $vals);
522 $circ->request('open-ils.circ.hold.update.batch.atomic', $e->authtoken, undef, $vlist)->gather(1);
529 sub load_myopac_holds {
531 my $e = $self->editor;
532 my $ctx = $self->ctx;
535 my $limit = $self->cgi->param('limit') || 0;
536 my $offset = $self->cgi->param('offset') || 0;
537 my $action = $self->cgi->param('action') || '';
539 $self->handle_hold_update($action) if $action;
541 $ctx->{holds} = $self->fetch_user_holds(undef, 0, 1, $limit, $offset);
543 return Apache2::Const::OK;
546 sub load_place_hold {
548 my $ctx = $self->ctx;
549 my $e = $self->editor;
550 $self->ctx->{page} = 'place_hold';
552 $ctx->{hold_target} = $self->cgi->param('hold_target');
553 $ctx->{hold_type} = $self->cgi->param('hold_type');
554 $ctx->{default_pickup_lib} = $e->requestor->home_ou; # XXX staff
556 if($ctx->{hold_type} eq 'T') {
557 $ctx->{record} = $e->retrieve_biblio_record_entry($ctx->{hold_target});
561 $ctx->{marc_xml} = XML::LibXML->new->parse_string($ctx->{record}->marc);
563 if(my $pickup_lib = $self->cgi->param('pickup_lib')) {
566 patronid => $e->requestor->id,
567 titleid => $ctx->{hold_target}, # XXX
568 pickup_lib => $pickup_lib,
572 my $allowed = $U->simplereq(
574 'open-ils.circ.title_hold.is_possible',
578 if($allowed->{success} == 1) {
579 my $hold = Fieldmapper::action::hold_request->new;
581 $hold->pickup_lib($pickup_lib);
582 $hold->requestor($e->requestor->id);
583 $hold->usr($e->requestor->id); # XXX staff
584 $hold->target($ctx->{hold_target});
585 $hold->hold_type($ctx->{hold_type});
586 # frozen, expired, etc..
588 my $stat = $U->simplereq(
590 'open-ils.circ.holds.create',
594 if($stat and $stat > 0) {
595 $ctx->{hold_success} = 1;
597 $ctx->{hold_failed} = 1; # XXX process the events, etc
601 # place the hold and deliver results
604 return Apache2::Const::OK;
608 sub fetch_user_circs {
610 my $flesh = shift; # flesh bib data, etc.
611 my $circ_ids = shift;
615 my $e = $self->editor;
620 @circ_ids = @$circ_ids;
624 my $circ_data = $U->simplereq(
626 'open-ils.actor.user.checked_out',
631 @circ_ids = ( @{$circ_data->{overdue}}, @{$circ_data->{out}} );
633 if($limit or $offset) {
634 @circ_ids = grep { defined $_ } @circ_ids[0..($offset + $limit - 1)];
638 return [] unless @circ_ids;
640 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
645 circ => ['target_copy'],
646 acp => ['call_number'],
652 my $circs = $e->search_action_circulation(
653 [{id => \@circ_ids}, ($flesh) ? $qflesh : {}], {substream => 1});
656 for my $circ (@$circs) {
659 marc_xml => ($flesh and $circ->target_copy->call_number->id != -1) ?
660 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc) :
661 undef # pre-cat copy, use the dummy title/author instead
666 # make sure the final list is in the correct order
668 for my $id (@circ_ids) {
671 (grep { $_->{circ}->id == $id } @circs)
675 return \@sorted_circs;
679 sub handle_circ_renew {
682 my $ctx = $self->ctx;
684 my @renew_ids = $self->cgi->param('circ');
686 my $circs = $self->fetch_user_circs(0, ($action eq 'renew') ? [@renew_ids] : undef);
688 # TODO: fire off renewal calls in batches to speed things up
690 for my $circ (@$circs) {
692 my $evt = $U->simplereq(
694 'open-ils.circ.renew',
695 $self->editor->authtoken,
697 patron_id => $self->editor->requestor->id,
698 copy_id => $circ->{circ}->target_copy,
703 # TODO return these, then insert them into the circ data
704 # blob that is shoved into the template for each circ
705 # so the template won't have to match them
706 push(@responses, {copy => $circ->{circ}->target_copy, evt => $evt});
713 sub load_myopac_circs {
715 my $e = $self->editor;
716 my $ctx = $self->ctx;
719 my $limit = $self->cgi->param('limit') || 0; # 0 == unlimited
720 my $offset = $self->cgi->param('offset') || 0;
721 my $action = $self->cgi->param('action') || '';
723 # perform the renewal first if necessary
724 my @results = $self->handle_circ_renew($action) if $action =~ /renew/;
726 $ctx->{circs} = $self->fetch_user_circs(1, undef, $limit, $offset);
728 my $success_renewals = 0;
729 my $failed_renewals = 0;
730 for my $data (@{$ctx->{circs}}) {
731 my ($resp) = grep { $_->{copy} == $data->{circ}->target_copy->id } @results;
734 my $evt = ref($resp->{evt}) eq 'ARRAY' ? $resp->{evt}->[0] : $resp->{evt};
735 $data->{renewal_response} = $evt;
736 $success_renewals++ if $evt->{textcode} eq 'SUCCESS';
737 $failed_renewals++ if $evt->{textcode} ne 'SUCCESS';
741 $ctx->{success_renewals} = $success_renewals;
742 $ctx->{failed_renewals} = $failed_renewals;
744 return Apache2::Const::OK;
747 sub load_myopac_fines {
749 my $e = $self->editor;
750 my $ctx = $self->ctx;
756 my $limit = $self->cgi->param('limit') || 0;
757 my $offset = $self->cgi->param('offset') || 0;
759 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
761 # TODO: This should really be a ML call, but the existing calls
762 # return an excessive amount of data and don't offer streaming
764 my %paging = ($limit or $offset) ? (limit => $limit, offset => $offset) : ();
766 my $req = $cstore->request(
767 'open-ils.cstore.direct.money.open_billable_transaction_summary.search',
769 usr => $e->requestor->id,
770 balance_owed => {'!=' => 0}
775 mobts => ['circulation', 'grocery'],
778 circ => ['target_copy'],
779 acp => ['call_number'],
782 order_by => { mobts => 'xact_start' },
787 while(my $resp = $req->recv) {
788 my $mobts = $resp->content;
789 my $circ = $mobts->circulation;
792 if($mobts->grocery) {
793 my @billings = sort { $a->billing_ts cmp $b->billing_ts } @{$mobts->grocery->billings};
794 $last_billing = pop(@billings);
798 @{$ctx->{"fines"}->{$mobts->grocery ? "grocery" : "circulation"}},
801 last_grocery_billing => $last_billing,
802 marc_xml => ($mobts->xact_type ne 'circulation' or $circ->target_copy->call_number->id == -1) ?
804 XML::LibXML->new->parse_string($circ->target_copy->call_number->record->marc),
809 return Apache2::Const::OK;