1 # ---------------------------------------------------------------
2 # Copyright (C) 2005 Georgia Public Library Service
3 # Bill Erickson <highfalutin@gmail.com>
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 # ---------------------------------------------------------------
17 package OpenILS::Application::Circ::Holds;
18 use base qw/OpenILS::Application/;
19 use strict; use warnings;
20 use OpenILS::Application::AppUtils;
23 use OpenSRF::EX qw(:try);
27 use OpenSRF::Utils::Logger qw(:logger);
28 use OpenILS::Utils::CStoreEditor q/:funcs/;
29 use OpenILS::Utils::PermitHold;
30 use OpenSRF::Utils::SettingsClient;
31 use OpenILS::Const qw/:const/;
32 use OpenILS::Application::Circ::Transit;
33 use OpenILS::Application::Actor::Friends;
35 use DateTime::Format::ISO8601;
36 use OpenSRF::Utils qw/:datetime/;
37 my $apputils = "OpenILS::Application::AppUtils";
43 __PACKAGE__->register_method(
44 method => "create_hold",
45 api_name => "open-ils.circ.holds.create",
47 Create a new hold for an item. From a permissions perspective,
48 the login session is used as the 'requestor' of the hold.
49 The hold recipient is determined by the 'usr' setting within
52 First we verify the requestion has holds request permissions.
53 Then we verify that the recipient is allowed to make the given hold.
54 If not, we see if the requestor has "override" capabilities. If not,
55 a permission exception is returned. If permissions allow, we cycle
56 through the set of holds objects and create.
58 If the recipient does not have permission to place multiple holds
59 on a single title and said operation is attempted, a permission
64 __PACKAGE__->register_method(
65 method => "create_hold",
66 api_name => "open-ils.circ.holds.create.override",
68 If the recipient is not allowed to receive the requested hold,
69 call this method to attempt the override
70 @see open-ils.circ.holds.create
75 my( $self, $conn, $auth, $hold ) = @_;
76 my $e = new_editor(authtoken=>$auth, xact=>1);
77 return $e->event unless $e->checkauth;
79 return -1 unless $hold;
80 my $override = 1 if $self->api_name =~ /override/;
84 my $requestor = $e->requestor;
85 my $recipient = $requestor;
87 if( $requestor->id ne $hold->usr ) {
88 # Make sure the requestor is allowed to place holds for
89 # the recipient if they are not the same people
90 $recipient = $e->retrieve_actor_user($hold->usr) or return $e->event;
91 $e->allowed('REQUEST_HOLDS', $recipient->home_ou) or return $e->event;
94 # Now make sure the recipient is allowed to receive the specified hold
96 my $porg = $recipient->home_ou;
97 my $rid = $e->requestor->id;
98 my $t = $hold->hold_type;
100 # See if a duplicate hold already exists
102 usr => $recipient->id,
104 fulfillment_time => undef,
105 target => $hold->target,
106 cancel_time => undef,
109 $sargs->{holdable_formats} = $hold->holdable_formats if $t eq 'M';
111 my $existing = $e->search_action_hold_request($sargs);
112 push( @events, OpenILS::Event->new('HOLD_EXISTS')) if @$existing;
114 if( $t eq OILS_HOLD_TYPE_METARECORD )
115 { $pevt = $e->event unless $e->allowed('MR_HOLDS', $porg); }
117 if( $t eq OILS_HOLD_TYPE_TITLE )
118 { $pevt = $e->event unless $e->allowed('TITLE_HOLDS', $porg); }
120 if( $t eq OILS_HOLD_TYPE_VOLUME )
121 { $pevt = $e->event unless $e->allowed('VOLUME_HOLDS', $porg); }
123 if( $t eq OILS_HOLD_TYPE_COPY )
124 { $pevt = $e->event unless $e->allowed('COPY_HOLDS', $porg); }
126 return $pevt if $pevt;
130 for my $evt (@events) {
132 my $name = $evt->{textcode};
133 return $e->event unless $e->allowed("$name.override", $porg);
140 # set the configured expire time
141 unless($hold->expire_time) {
142 my $interval = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_HOLD_EXPIRE);
144 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
145 $hold->expire_time($U->epoch2ISO8601($date->epoch));
149 $hold->requestor($e->requestor->id);
150 $hold->request_lib($e->requestor->ws_ou);
151 $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
152 $hold = $e->create_action_hold_request($hold) or return $e->event;
156 $conn->respond_complete($hold->id);
159 'open-ils.storage.action.hold_request.copy_targeter',
160 undef, $hold->id ) unless $U->is_true($hold->frozen);
166 my( $self, $client, $login_session, @holds) = @_;
168 if(!@holds){return 0;}
169 my( $user, $evt ) = $apputils->checkses($login_session);
173 if(ref($holds[0]) eq 'ARRAY') {
175 } else { $holds = [ @holds ]; }
177 $logger->debug("Iterating over holds requests...");
179 for my $hold (@$holds) {
182 my $type = $hold->hold_type;
184 $logger->activity("User " . $user->id .
185 " creating new hold of type $type for user " . $hold->usr);
188 if($user->id ne $hold->usr) {
189 ( $recipient, $evt ) = $apputils->fetch_user($hold->usr);
199 # am I allowed to place holds for this user?
200 if($hold->requestor ne $hold->usr) {
201 $perm = _check_request_holds_perm($user->id, $user->home_ou);
202 if($perm) { return $perm; }
205 # is this user allowed to have holds of this type?
206 $perm = _check_holds_perm($type, $hold->requestor, $recipient->home_ou);
207 return $perm if $perm;
209 #enforce the fact that the login is the one requesting the hold
210 $hold->requestor($user->id);
211 $hold->selection_ou($recipient->home_ou) unless $hold->selection_ou;
213 my $resp = $apputils->simplereq(
215 'open-ils.storage.direct.action.hold_request.create', $hold );
218 return OpenSRF::EX::ERROR ("Error creating hold");
225 # makes sure that a user has permission to place the type of requested hold
226 # returns the Perm exception if not allowed, returns undef if all is well
227 sub _check_holds_perm {
228 my($type, $user_id, $org_id) = @_;
232 if($evt = $apputils->check_perms(
233 $user_id, $org_id, "MR_HOLDS")) {
237 } elsif ($type eq "T") {
238 if($evt = $apputils->check_perms(
239 $user_id, $org_id, "TITLE_HOLDS")) {
243 } elsif($type eq "V") {
244 if($evt = $apputils->check_perms(
245 $user_id, $org_id, "VOLUME_HOLDS")) {
249 } elsif($type eq "C") {
250 if($evt = $apputils->check_perms(
251 $user_id, $org_id, "COPY_HOLDS")) {
259 # tests if the given user is allowed to place holds on another's behalf
260 sub _check_request_holds_perm {
263 if(my $evt = $apputils->check_perms(
264 $user_id, $org_id, "REQUEST_HOLDS")) {
269 __PACKAGE__->register_method(
270 method => "retrieve_holds_by_id",
271 api_name => "open-ils.circ.holds.retrieve_by_id",
273 Retrieve the hold, with hold transits attached, for the specified id The login session is the requestor and if the requestor is
274 different from the user, then the requestor must have VIEW_HOLD permissions.
278 sub retrieve_holds_by_id {
279 my($self, $client, $auth, $hold_id) = @_;
280 my $e = new_editor(authtoken=>$auth);
281 $e->checkauth or return $e->event;
282 $e->allowed('VIEW_HOLD') or return $e->event;
284 my $holds = $e->search_action_hold_request(
286 { id => $hold_id , fulfillment_time => undef },
288 order_by => { ahr => "request_time" },
290 flesh_fields => {ahr => ['notes']}
295 flesh_hold_transits($holds);
296 flesh_hold_notices($holds, $e);
301 __PACKAGE__->register_method(
302 method => "retrieve_holds",
303 api_name => "open-ils.circ.holds.retrieve",
305 Retrieves all the holds, with hold transits attached, for the specified
306 user id. The login session is the requestor and if the requestor is
307 different from the user, then the requestor must have VIEW_HOLD permissions.
310 __PACKAGE__->register_method(
311 method => "retrieve_holds",
313 api_name => "open-ils.circ.holds.id_list.retrieve",
315 Retrieves all the hold ids for the specified
316 user id. The login session is the requestor and if the requestor is
317 different from the user, then the requestor must have VIEW_HOLD permissions.
321 __PACKAGE__->register_method(
322 method => "retrieve_holds",
324 api_name => "open-ils.circ.holds.canceled.retrieve",
327 __PACKAGE__->register_method(
328 method => "retrieve_holds",
330 api_name => "open-ils.circ.holds.canceled.id_list.retrieve",
335 my($self, $client, $auth, $user_id, $options) = @_;
337 my $e = new_editor(authtoken=>$auth);
338 return $e->event unless $e->checkauth;
339 $user_id = $e->requestor->id unless defined $user_id;
342 unless($user_id == $e->requestor->id) {
343 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
344 unless($e->allowed('VIEW_HOLD', $user->home_ou)) {
345 my $allowed = OpenILS::Application::Actor::Friends->friend_perm_allowed(
346 $e, $user_id, $e->requestor->id, 'hold.view');
347 return $e->event unless $allowed;
353 if($self->api_name !~ /canceled/) {
355 # Fetch the active holds
357 $holds = $e->search_action_hold_request([
359 fulfillment_time => undef,
360 cancel_time => undef,
362 {order_by => {ahr => "request_time"}}
367 # Fetch the canceled holds
371 $U->ou_ancestor_setting_value(
372 $e->requestor->ws_ou, 'circ.holds.canceled.display_count', $e);
374 unless($cancel_count) {
375 $cancel_age = $U->ou_ancestor_setting_value(
376 $e->requestor->ws_ou, 'circ.holds.canceled.display_age', $e);
379 if($cancel_count) { # limit by count
381 # find at most cancel_count canceled holds
382 $holds = $e->search_action_hold_request([
384 fulfillment_time => undef,
385 cancel_time => {'!=' => undef},
387 {order_by => {ahr => "cancel_time desc"}, limit => $cancel_count}
390 } elsif($cancel_age) { # limit by age
392 # find all of the canceled holds that were canceled within the configured time frame
393 my $date = DateTime->now->subtract(seconds => OpenSRF::Utils::interval_to_seconds($cancel_age));
394 $date = $U->epoch2ISO8601($date->epoch);
396 $holds = $e->search_action_hold_request([
398 fulfillment_time => undef,
399 cancel_time => {'>=' => $date},
401 {order_by => {ahr => "cancel_time desc"}}
406 if( ! $self->api_name =~ /id_list/ ) {
407 for my $hold ( @$holds ) {
409 $e->search_action_hold_transit_copy([
411 {order_by => {ahtc => 'id desc'}, limit => 1}])->[0]
416 if( $self->api_name =~ /id_list/ ) {
417 return [ map { $_->id } @$holds ];
424 __PACKAGE__->register_method(
425 method => 'user_hold_count',
426 api_name => 'open-ils.circ.hold.user.count');
428 sub user_hold_count {
429 my( $self, $conn, $auth, $userid ) = @_;
430 my $e = new_editor(authtoken=>$auth);
431 return $e->event unless $e->checkauth;
432 my $patron = $e->retrieve_actor_user($userid)
434 return $e->event unless $e->allowed('VIEW_HOLD', $patron->home_ou);
435 return __user_hold_count($self, $e, $userid);
438 sub __user_hold_count {
439 my( $self, $e, $userid ) = @_;
440 my $holds = $e->search_action_hold_request(
442 fulfillment_time => undef,
443 cancel_time => undef,
448 return scalar(@$holds);
452 __PACKAGE__->register_method(
453 method => "retrieve_holds_by_pickup_lib",
454 api_name => "open-ils.circ.holds.retrieve_by_pickup_lib",
456 Retrieves all the holds, with hold transits attached, for the specified
460 __PACKAGE__->register_method(
461 method => "retrieve_holds_by_pickup_lib",
462 api_name => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
464 Retrieves all the hold ids for the specified
468 sub retrieve_holds_by_pickup_lib {
469 my($self, $client, $login_session, $ou_id) = @_;
471 #FIXME -- put an appropriate permission check here
472 #my( $user, $target, $evt ) = $apputils->checkses_requestor(
473 # $login_session, $user_id, 'VIEW_HOLD' );
474 #return $evt if $evt;
476 my $holds = $apputils->simplereq(
478 "open-ils.cstore.direct.action.hold_request.search.atomic",
480 pickup_lib => $ou_id ,
481 fulfillment_time => undef,
484 { order_by => { ahr => "request_time" } });
487 if( ! $self->api_name =~ /id_list/ ) {
488 flesh_hold_transits($holds);
491 if( $self->api_name =~ /id_list/ ) {
492 return [ map { $_->id } @$holds ];
499 __PACKAGE__->register_method(
500 method => "uncancel_hold",
501 api_name => "open-ils.circ.hold.uncancel"
505 my($self, $client, $auth, $hold_id) = @_;
506 my $e = new_editor(authtoken=>$auth, xact=>1);
507 return $e->event unless $e->checkauth;
509 my $hold = $e->retrieve_action_hold_request($hold_id)
510 or return $e->die_event;
511 return $e->die_event unless $e->allowed('CANCEL_HOLDS', $hold->request_lib);
513 return 0 if $hold->fulfillment_time;
514 return 1 unless $hold->cancel_time;
516 # if configured to reset the request time, also reset the expire time
517 if($U->ou_ancestor_setting_value(
518 $hold->request_lib, 'circ.holds.uncancel.reset_request_time', $e)) {
520 $hold->request_time('now');
521 my $interval = $U->ou_ancestor_setting_value($hold->request_lib, OILS_SETTING_HOLD_EXPIRE);
523 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
524 $hold->expire_time($U->epoch2ISO8601($date->epoch));
528 $hold->clear_cancel_time;
529 $hold->clear_cancel_cause;
530 $hold->clear_cancel_note;
531 $e->update_action_hold_request($hold) or return $e->die_event;
534 $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
540 __PACKAGE__->register_method(
541 method => "cancel_hold",
542 api_name => "open-ils.circ.hold.cancel",
544 Cancels the specified hold. The login session
545 is the requestor and if the requestor is different from the usr field
546 on the hold, the requestor must have CANCEL_HOLDS permissions.
547 the hold may be either the hold object or the hold id
551 my($self, $client, $auth, $holdid, $cause, $note) = @_;
553 my $e = new_editor(authtoken=>$auth, xact=>1);
554 return $e->event unless $e->checkauth;
556 my $hold = $e->retrieve_action_hold_request($holdid)
559 if( $e->requestor->id ne $hold->usr ) {
560 return $e->event unless $e->allowed('CANCEL_HOLDS');
563 return 1 if $hold->cancel_time;
565 # If the hold is captured, reset the copy status
566 if( $hold->capture_time and $hold->current_copy ) {
568 my $copy = $e->retrieve_asset_copy($hold->current_copy)
571 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
572 $logger->info("canceling hold $holdid whose item is on the holds shelf");
573 # $logger->info("setting copy to status 'reshelving' on hold cancel");
574 # $copy->status(OILS_COPY_STATUS_RESHELVING);
575 # $copy->editor($e->requestor->id);
576 # $copy->edit_date('now');
577 # $e->update_asset_copy($copy) or return $e->event;
579 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
582 $logger->warn("! canceling hold [$hid] that is in transit");
583 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
586 my $trans = $e->retrieve_action_transit_copy($transid);
587 # Leave the transit alive, but set the copy status to
588 # reshelving so it will be properly reshelved when it gets back home
590 $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
591 $e->update_action_transit_copy($trans) or return $e->die_event;
597 $hold->cancel_time('now');
598 $hold->cancel_cause($cause);
599 $hold->cancel_note($note);
600 $e->update_action_hold_request($hold)
603 delete_hold_copy_maps($self, $e, $hold->id);
609 sub delete_hold_copy_maps {
614 my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
616 $editor->delete_action_hold_copy_map($_)
617 or return $editor->event;
623 __PACKAGE__->register_method(
624 method => "update_hold",
625 api_name => "open-ils.circ.hold.update",
627 Updates the specified hold. The login session
628 is the requestor and if the requestor is different from the usr field
629 on the hold, the requestor must have UPDATE_HOLDS permissions.
632 __PACKAGE__->register_method(
633 method => "batch_update_hold",
634 api_name => "open-ils.circ.hold.update.batch",
637 Updates the specified hold. The login session
638 is the requestor and if the requestor is different from the usr field
639 on the hold, the requestor must have UPDATE_HOLDS permissions.
643 my($self, $client, $auth, $hold, $values) = @_;
644 my $e = new_editor(authtoken=>$auth, xact=>1);
645 return $e->die_event unless $e->checkauth;
646 my $resp = update_hold_impl($self, $e, $hold, $values);
647 return $resp if $U->event_code($resp);
652 sub batch_update_hold {
653 my($self, $client, $auth, $hold_list, $values_list) = @_;
654 my $e = new_editor(authtoken=>$auth);
655 return $e->die_event unless $e->checkauth;
657 my $count = ($hold_list) ? scalar(@$hold_list) : scalar(@$values_list);
661 for my $idx (0..$count-1) {
663 my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
664 $e->xact_commit unless $U->event_code($resp);
665 $client->respond($resp);
672 sub update_hold_impl {
673 my($self, $e, $hold, $values) = @_;
676 $hold = $e->retrieve_action_hold_request($values->{id})
677 or return $e->die_event;
678 $hold->$_($values->{$_}) for keys %$values;
681 my $orig_hold = $e->retrieve_action_hold_request($hold->id)
682 or return $e->die_event;
684 # don't allow the user to be changed
685 return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
687 if($hold->usr ne $e->requestor->id) {
688 # if the hold is for a different user, make sure the
689 # requestor has the appropriate permissions
690 my $usr = $e->retrieve_actor_user($hold->usr)
691 or return $e->die_event;
692 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
696 # --------------------------------------------------------------
697 # Changing the request time is like playing God
698 # --------------------------------------------------------------
699 if($hold->request_time ne $orig_hold->request_time) {
700 return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
701 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
704 # --------------------------------------------------------------
705 # if the hold is on the holds shelf or in transit and the pickup
706 # lib changes we need to create a new transit.
707 # --------------------------------------------------------------
708 if($orig_hold->pickup_lib ne $hold->pickup_lib) {
710 my $status = _hold_status($e, $hold);
712 if($status == 3) { # in transit
714 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
715 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
717 $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
719 # update the transit to reflect the new pickup location
720 my $transit = $e->search_action_hold_transit_copy(
721 {hold=>$hold->id, dest_recv_time => undef})->[0]
722 or return $e->die_event;
724 $transit->prev_dest($transit->dest); # mark the previous destination on the transit
725 $transit->dest($hold->pickup_lib);
726 $e->update_action_hold_transit_copy($transit) or return $e->die_event;
728 } elsif($status == 4) { # on holds shelf
730 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
731 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
733 $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
735 # create the new transit
736 my $evt = transit_hold($e, $orig_hold, $hold, $e->retrieve_asset_copy($hold->current_copy));
741 update_hold_if_frozen($self, $e, $hold, $orig_hold);
742 $e->update_action_hold_request($hold) or return $e->die_event;
745 # a change to mint-condition changes the set of potential copies, so retarget the hold;
746 if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
747 _reset_hold($self, $e->requestor, $hold)
754 my($e, $orig_hold, $hold, $copy) = @_;
755 my $src = $orig_hold->pickup_lib;
756 my $dest = $hold->pickup_lib;
758 $logger->info("putting hold into transit on pickup_lib update");
760 my $transit = Fieldmapper::action::hold_transit_copy->new;
761 $transit->hold($hold->id);
762 $transit->source($src);
763 $transit->dest($dest);
764 $transit->target_copy($copy->id);
765 $transit->source_send_time('now');
766 $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
768 $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
769 $copy->editor($e->requestor->id);
770 $copy->edit_date('now');
772 $e->create_action_hold_transit_copy($transit) or return $e->die_event;
773 $e->update_asset_copy($copy) or return $e->die_event;
777 # if the hold is frozen, this method ensures that the hold is not "targeted",
778 # that is, it clears the current_copy and prev_check_time to essentiallly
779 # reset the hold. If it is being activated, it runs the targeter in the background
780 sub update_hold_if_frozen {
781 my($self, $e, $hold, $orig_hold) = @_;
782 return if $hold->capture_time;
784 if($U->is_true($hold->frozen)) {
785 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
786 $hold->clear_current_copy;
787 $hold->clear_prev_check_time;
790 if($U->is_true($orig_hold->frozen)) {
791 $logger->info("Running targeter on activated hold ".$hold->id);
792 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
796 __PACKAGE__->register_method(
797 method => "hold_note_CUD",
798 api_name => "open-ils.circ.hold_request.note.cud");
801 my($self, $conn, $auth, $note) = @_;
803 my $e = new_editor(authtoken => $auth, xact => 1);
804 return $e->die_event unless $e->checkauth;
806 my $hold = $e->retrieve_action_hold_request($note->hold)
807 or return $e->die_event;
809 if($hold->usr ne $e->requestor->id) {
810 my $usr = $e->retrieve_actor_user($hold->usr);
811 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
812 $note->staff('t') if $note->isnew;
816 $e->create_action_hold_request_note($note) or return $e->die_event;
817 } elsif($note->ischanged) {
818 $e->update_action_hold_request_note($note) or return $e->die_event;
819 } elsif($note->isdeleted) {
820 $e->delete_action_hold_request_note($note) or return $e->die_event;
829 __PACKAGE__->register_method(
830 method => "retrieve_hold_status",
831 api_name => "open-ils.circ.hold.status.retrieve",
833 Calculates the current status of the hold.
834 the requestor must have VIEW_HOLD permissions if the hold is for a user
835 other than the requestor.
836 Returns -1 on error (for now)
837 Returns 1 for 'waiting for copy to become available'
838 Returns 2 for 'waiting for copy capture'
839 Returns 3 for 'in transit'
840 Returns 4 for 'arrived'
841 Returns 5 for 'hold-shelf-delay'
844 sub retrieve_hold_status {
845 my($self, $client, $auth, $hold_id) = @_;
847 my $e = new_editor(authtoken => $auth);
848 return $e->event unless $e->checkauth;
849 my $hold = $e->retrieve_action_hold_request($hold_id)
852 if( $e->requestor->id != $hold->usr ) {
853 return $e->event unless $e->allowed('VIEW_HOLD');
856 return _hold_status($e, $hold);
862 return 1 unless $hold->current_copy;
863 return 2 unless $hold->capture_time;
865 my $copy = $hold->current_copy;
866 unless( ref $copy ) {
867 $copy = $e->retrieve_asset_copy($hold->current_copy)
871 return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
873 if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
875 my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
876 return 4 unless $hs_wait_interval;
878 # if a hold_shelf_status_delay interval is defined and start_time plus
879 # the interval is greater than now, consider the hold to be in the virtual
880 # "on its way to the holds shelf" status. Return 5.
882 my $transit = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
883 my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
884 $start_time = DateTime::Format::ISO8601->new->parse_datetime(clense_ISO8601($start_time));
885 my $end_time = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
887 return 5 if $end_time > DateTime->now;
896 __PACKAGE__->register_method(
897 method => "retrieve_hold_queue_stats",
898 api_name => "open-ils.circ.hold.queue_stats.retrieve",
901 Returns object with total_holds count, queue_position, potential_copies count, and status code
906 sub retrieve_hold_queue_stats {
907 my($self, $conn, $auth, $hold_id) = @_;
908 my $e = new_editor(authtoken => $auth);
909 return $e->event unless $e->checkauth;
910 my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
911 if($e->requestor->id != $hold->usr) {
912 return $e->event unless $e->allowed('VIEW_HOLD');
914 return retrieve_hold_queue_status_impl($e, $hold);
917 sub retrieve_hold_queue_status_impl {
921 # The holds queue is defined as the set of holds that share at
922 # least one potential copy with the context hold
923 my $q_holds = $e->json_query({
926 # fetch request_time since it's in the order_by and we're asking for distinct values
927 ahr => ['request_time']
929 from => {ahcm => 'ahr'},
930 order_by => {ahr => ['request_time']},
935 select => {ahcm => ['target_copy']},
937 where => {hold => $hold->id}
944 for my $h (@$q_holds) {
945 last if $h->{hold} == $hold->id;
949 # total count of potential copies
950 my $num_potentials = $e->json_query({
951 select => {ahcm => [{column => 'id', transform => 'count', alias => 'count'}]},
953 where => {hold => $hold->id}
956 my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
957 my $default_hold_interval = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
958 my $estimated_wait = $qpos * ($default_hold_interval / $num_potentials) if $default_hold_interval;
961 total_holds => scalar(@$q_holds),
962 queue_position => $qpos,
963 potential_copies => $num_potentials->{count},
964 status => _hold_status($e, $hold),
965 estimated_wait => int($estimated_wait)
970 sub fetch_open_hold_by_current_copy {
973 my $hold = $apputils->simplereq(
975 'open-ils.cstore.direct.action.hold_request.search.atomic',
976 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
977 return $hold->[0] if ref($hold);
981 sub fetch_related_holds {
984 return $apputils->simplereq(
986 'open-ils.cstore.direct.action.hold_request.search.atomic',
987 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
991 __PACKAGE__->register_method (
992 method => "hold_pull_list",
993 api_name => "open-ils.circ.hold_pull_list.retrieve",
995 Returns a list of holds that need to be "pulled"
1000 __PACKAGE__->register_method (
1001 method => "hold_pull_list",
1002 api_name => "open-ils.circ.hold_pull_list.id_list.retrieve",
1004 Returns a list of hold ID's that need to be "pulled"
1009 __PACKAGE__->register_method (
1010 method => "hold_pull_list",
1011 api_name => "open-ils.circ.hold_pull_list.retrieve.count",
1013 Returns a list of holds that need to be "pulled"
1019 sub hold_pull_list {
1020 my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1021 my( $reqr, $evt ) = $U->checkses($authtoken);
1022 return $evt if $evt;
1024 my $org = $reqr->ws_ou || $reqr->home_ou;
1025 # the perm locaiton shouldn't really matter here since holds
1026 # will exist all over and VIEW_HOLDS should be universal
1027 $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1028 return $evt if $evt;
1030 if($self->api_name =~ /count/) {
1032 my $count = $U->storagereq(
1033 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1034 $org, $limit, $offset );
1036 $logger->info("Grabbing pull list for org unit $org with $count items");
1039 } elsif( $self->api_name =~ /id_list/ ) {
1040 return $U->storagereq(
1041 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1042 $org, $limit, $offset );
1045 return $U->storagereq(
1046 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1047 $org, $limit, $offset );
1051 __PACKAGE__->register_method (
1052 method => 'fetch_hold_notify',
1053 api_name => 'open-ils.circ.hold_notification.retrieve_by_hold',
1056 Returns a list of hold notification objects based on hold id.
1057 @param authtoken The loggin session key
1058 @param holdid The id of the hold whose notifications we want to retrieve
1059 @return An array of hold notification objects, event on error.
1063 sub fetch_hold_notify {
1064 my( $self, $conn, $authtoken, $holdid ) = @_;
1065 my( $requestor, $evt ) = $U->checkses($authtoken);
1066 return $evt if $evt;
1067 my ($hold, $patron);
1068 ($hold, $evt) = $U->fetch_hold($holdid);
1069 return $evt if $evt;
1070 ($patron, $evt) = $U->fetch_user($hold->usr);
1071 return $evt if $evt;
1073 $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1074 return $evt if $evt;
1076 $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1077 return $U->cstorereq(
1078 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1082 __PACKAGE__->register_method (
1083 method => 'create_hold_notify',
1084 api_name => 'open-ils.circ.hold_notification.create',
1086 Creates a new hold notification object
1087 @param authtoken The login session key
1088 @param notification The hold notification object to create
1089 @return ID of the new object on success, Event on error
1093 sub create_hold_notify {
1094 my( $self, $conn, $auth, $note ) = @_;
1095 my $e = new_editor(authtoken=>$auth, xact=>1);
1096 return $e->die_event unless $e->checkauth;
1098 my $hold = $e->retrieve_action_hold_request($note->hold)
1099 or return $e->die_event;
1100 my $patron = $e->retrieve_actor_user($hold->usr)
1101 or return $e->die_event;
1103 return $e->die_event unless
1104 $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1106 $note->notify_staff($e->requestor->id);
1107 $e->create_action_hold_notification($note) or return $e->die_event;
1112 __PACKAGE__->register_method (
1113 method => 'create_hold_note',
1114 api_name => 'open-ils.circ.hold_note.create',
1116 Creates a new hold request note object
1117 @param authtoken The login session key
1118 @param note The hold note object to create
1119 @return ID of the new object on success, Event on error
1123 sub create_hold_note {
1124 my( $self, $conn, $auth, $note ) = @_;
1125 my $e = new_editor(authtoken=>$auth, xact=>1);
1126 return $e->die_event unless $e->checkauth;
1128 my $hold = $e->retrieve_action_hold_request($note->hold)
1129 or return $e->die_event;
1130 my $patron = $e->retrieve_actor_user($hold->usr)
1131 or return $e->die_event;
1133 return $e->die_event unless
1134 $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn. Probably want something more specific
1136 $e->create_action_hold_request_note($note) or return $e->die_event;
1141 __PACKAGE__->register_method(
1142 method => 'reset_hold',
1143 api_name => 'open-ils.circ.hold.reset',
1145 Un-captures and un-targets a hold, essentially returning
1146 it to the state it was in directly after it was placed,
1147 then attempts to re-target the hold
1148 @param authtoken The login session key
1149 @param holdid The id of the hold
1155 my( $self, $conn, $auth, $holdid ) = @_;
1157 my ($hold, $evt) = $U->fetch_hold($holdid);
1158 return $evt if $evt;
1159 ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1160 return $evt if $evt;
1161 $evt = _reset_hold($self, $reqr, $hold);
1162 return $evt if $evt;
1167 __PACKAGE__->register_method(
1168 method => 'reset_hold_batch',
1169 api_name => 'open-ils.circ.hold.reset.batch'
1172 sub reset_hold_batch {
1173 my($self, $conn, $auth, $hold_ids) = @_;
1175 my $e = new_editor(authtoken => $auth);
1176 return $e->event unless $e->checkauth;
1178 for my $hold_id ($hold_ids) {
1180 my $hold = $e->retrieve_action_hold_request(
1181 [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}])
1182 or return $e->event;
1184 next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1185 _reset_hold($self, $e->requestor, $hold);
1193 my ($self, $reqr, $hold) = @_;
1195 my $e = new_editor(xact =>1, requestor => $reqr);
1197 $logger->info("reseting hold ".$hold->id);
1199 my $hid = $hold->id;
1201 if( $hold->capture_time and $hold->current_copy ) {
1203 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1204 or return $e->event;
1206 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1207 $logger->info("setting copy to status 'reshelving' on hold retarget");
1208 $copy->status(OILS_COPY_STATUS_RESHELVING);
1209 $copy->editor($e->requestor->id);
1210 $copy->edit_date('now');
1211 $e->update_asset_copy($copy) or return $e->event;
1213 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1215 # We don't want the copy to remain "in transit"
1216 $copy->status(OILS_COPY_STATUS_RESHELVING);
1217 $logger->warn("! reseting hold [$hid] that is in transit");
1218 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1221 my $trans = $e->retrieve_action_transit_copy($transid);
1223 $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1224 my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1);
1225 $logger->info("Transit abort completed with result $evt");
1226 return $evt unless "$evt" eq 1;
1232 $hold->clear_capture_time;
1233 $hold->clear_current_copy;
1234 $hold->clear_shelf_time;
1235 $hold->clear_shelf_expire_time;
1237 $e->update_action_hold_request($hold) or return $e->event;
1241 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1247 __PACKAGE__->register_method(
1248 method => 'fetch_open_title_holds',
1249 api_name => 'open-ils.circ.open_holds.retrieve',
1251 Returns a list ids of un-fulfilled holds for a given title id
1252 @param authtoken The login session key
1253 @param id the id of the item whose holds we want to retrieve
1254 @param type The hold type - M, T, V, C
1258 sub fetch_open_title_holds {
1259 my( $self, $conn, $auth, $id, $type, $org ) = @_;
1260 my $e = new_editor( authtoken => $auth );
1261 return $e->event unless $e->checkauth;
1264 $org ||= $e->requestor->ws_ou;
1266 # return $e->search_action_hold_request(
1267 # { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1269 # XXX make me return IDs in the future ^--
1270 my $holds = $e->search_action_hold_request(
1273 cancel_time => undef,
1275 fulfillment_time => undef
1279 flesh_hold_transits($holds);
1284 sub flesh_hold_transits {
1286 for my $hold ( @$holds ) {
1288 $apputils->simplereq(
1290 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1291 { hold => $hold->id },
1292 { order_by => { ahtc => 'id desc' }, limit => 1 }
1298 sub flesh_hold_notices {
1299 my( $holds, $e ) = @_;
1300 $e ||= new_editor();
1302 for my $hold (@$holds) {
1303 my $notices = $e->search_action_hold_notification(
1305 { hold => $hold->id },
1306 { order_by => { anh => 'notify_time desc' } },
1311 $hold->notify_count(scalar(@$notices));
1313 my $n = $e->retrieve_action_hold_notification($$notices[0])
1314 or return $e->event;
1315 $hold->notify_time($n->notify_time);
1321 __PACKAGE__->register_method(
1322 method => 'fetch_captured_holds',
1323 api_name => 'open-ils.circ.captured_holds.on_shelf.retrieve',
1326 Returns a list of un-fulfilled holds for a given title id
1327 @param authtoken The login session key
1328 @param org The org id of the location in question
1332 __PACKAGE__->register_method(
1333 method => 'fetch_captured_holds',
1334 api_name => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
1337 Returns a list ids of un-fulfilled holds for a given title id
1338 @param authtoken The login session key
1339 @param org The org id of the location in question
1343 sub fetch_captured_holds {
1344 my( $self, $conn, $auth, $org ) = @_;
1346 my $e = new_editor(authtoken => $auth);
1347 return $e->event unless $e->checkauth;
1348 return $e->event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
1350 $org ||= $e->requestor->ws_ou;
1352 my $hold_ids = $e->json_query(
1354 select => { ahr => ['id'] },
1359 fkey => 'current_copy'
1364 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
1366 capture_time => { "!=" => undef },
1367 current_copy => { "!=" => undef },
1368 fulfillment_time => undef,
1370 cancel_time => undef,
1376 for my $hold_id (@$hold_ids) {
1377 if($self->api_name =~ /id_list/) {
1378 $conn->respond($hold_id->{id});
1382 $e->retrieve_action_hold_request([
1386 flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
1387 order_by => {anh => 'notify_time desc'}
1396 __PACKAGE__->register_method(
1397 method => "check_title_hold",
1398 api_name => "open-ils.circ.title_hold.is_possible",
1400 Determines if a hold were to be placed by a given user,
1401 whether or not said hold would have any potential copies
1403 @param authtoken The login session key
1404 @param params A hash of named params including:
1405 patronid - the id of the hold recipient
1406 titleid (brn) - the id of the title to be held
1407 depth - the hold range depth (defaults to 0)
1410 sub check_title_hold {
1411 my( $self, $client, $authtoken, $params ) = @_;
1413 my %params = %$params;
1414 my $titleid = $params{titleid} ||"";
1415 my $volid = $params{volume_id};
1416 my $copyid = $params{copy_id};
1417 my $mrid = $params{mrid} ||"";
1418 my $depth = $params{depth} || 0;
1419 my $pickup_lib = $params{pickup_lib};
1420 my $hold_type = $params{hold_type} || 'T';
1421 my $selection_ou = $params{selection_ou} || $pickup_lib;
1423 my $e = new_editor(authtoken=>$authtoken);
1424 return $e->event unless $e->checkauth;
1425 my $patron = $e->retrieve_actor_user($params{patronid})
1426 or return $e->event;
1428 if( $e->requestor->id ne $patron->id ) {
1429 return $e->event unless
1430 $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
1433 return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
1435 my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
1436 or return $e->event;
1438 my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
1439 my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
1441 if(defined $soft_boundary and $$params{depth} < $soft_boundary) {
1442 # work up the tree and as soon as we find a potential copy, use that depth
1443 # also, make sure we don't go past the hard boundary if it exists
1445 # our min boundary is the greater of user-specified boundary or hard boundary
1446 my $min_depth = (defined $hard_boundary and $hard_boundary > $$params{depth}) ?
1447 $hard_boundary : $$params{depth};
1449 my $depth = $soft_boundary;
1450 while($depth >= $min_depth) {
1451 $logger->info("performing hold possibility check with soft boundary $depth");
1452 my @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
1453 return {success => 1, depth => $depth, local_avail => $status[1]} if $status[0];
1456 return {success => 0};
1458 } elsif(defined $hard_boundary and $$params{depth} < $hard_boundary) {
1459 # there is no soft boundary, enforce the hard boundary if it exists
1460 $logger->info("performing hold possibility check with hard boundary $hard_boundary");
1461 my @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
1463 return {success => 1, depth => $hard_boundary, local_avail => $status[1]}
1465 return {success => 0};
1469 # no boundaries defined, fall back to user specifed boundary or no boundary
1470 $logger->info("performing hold possibility check with no boundary");
1471 my @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
1473 return {success => 1, depth => $hard_boundary, local_avail => $status[1]};
1475 return {success => 0};
1480 sub do_possibility_checks {
1481 my($e, $patron, $request_lib, $depth, %params) = @_;
1483 my $titleid = $params{titleid} ||"";
1484 my $volid = $params{volume_id};
1485 my $copyid = $params{copy_id};
1486 my $mrid = $params{mrid} ||"";
1487 my $pickup_lib = $params{pickup_lib};
1488 my $hold_type = $params{hold_type} || 'T';
1489 my $selection_ou = $params{selection_ou} || $pickup_lib;
1496 if( $hold_type eq OILS_HOLD_TYPE_COPY ) {
1498 $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
1499 $volume = $e->retrieve_asset_call_number($copy->call_number)
1500 or return $e->event;
1501 $title = $e->retrieve_biblio_record_entry($volume->record)
1502 or return $e->event;
1503 return verify_copy_for_hold(
1504 $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib );
1506 } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
1508 $volume = $e->retrieve_asset_call_number($volid)
1509 or return $e->event;
1510 $title = $e->retrieve_biblio_record_entry($volume->record)
1511 or return $e->event;
1513 return _check_volume_hold_is_possible(
1514 $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou);
1516 } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
1518 return _check_title_hold_is_possible(
1519 $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou);
1521 } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
1523 my $maps = $e->search_metabib_source_map({metarecord=>$mrid});
1524 my @recs = map { $_->source } @$maps;
1525 for my $rec (@recs) {
1526 my @status = _check_title_hold_is_possible(
1527 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou);
1528 return @status if $status[1];
1535 sub create_ranged_org_filter {
1536 my($e, $selection_ou, $depth) = @_;
1538 # find the orgs from which this hold may be fulfilled,
1539 # based on the selection_ou and depth
1541 my $top_org = $e->search_actor_org_unit([
1542 {parent_ou => undef},
1543 {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
1546 return () if $depth == $top_org->ou_type->depth;
1548 my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
1549 %org_filter = (circ_lib => []);
1550 push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
1552 $logger->info("hold org filter at depth $depth and selection_ou ".
1553 "$selection_ou created list of @{$org_filter{circ_lib}}");
1559 sub _check_title_hold_is_possible {
1560 my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
1562 my $e = new_editor();
1563 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
1565 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
1566 my $copies = $e->json_query(
1568 select => { acp => ['id', 'circ_lib'] },
1573 fkey => 'call_number',
1577 filter => { id => $titleid },
1582 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
1583 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
1587 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
1592 $logger->info("title possible found ".scalar(@$copies)." potential copies");
1593 return (0) unless @$copies;
1595 # -----------------------------------------------------------------------
1596 # sort the copies into buckets based on their circ_lib proximity to
1597 # the patron's home_ou.
1598 # -----------------------------------------------------------------------
1600 my $home_org = $patron->home_ou;
1601 my $req_org = $request_lib->id;
1603 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
1605 $prox_cache{$home_org} =
1606 $e->search_actor_org_unit_proximity({from_org => $home_org})
1607 unless $prox_cache{$home_org};
1608 my $home_prox = $prox_cache{$home_org};
1611 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
1612 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1614 my @keys = sort { $a <=> $b } keys %buckets;
1617 if( $home_org ne $req_org ) {
1618 # -----------------------------------------------------------------------
1619 # shove the copies close to the request_lib into the primary buckets
1620 # directly before the farthest away copies. That way, they are not
1621 # given priority, but they are checked before the farthest copies.
1622 # -----------------------------------------------------------------------
1623 $prox_cache{$req_org} =
1624 $e->search_actor_org_unit_proximity({from_org => $req_org})
1625 unless $prox_cache{$req_org};
1626 my $req_prox = $prox_cache{$req_org};
1630 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
1631 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1633 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
1634 my $new_key = $highest_key - 0.5; # right before the farthest prox
1635 my @keys2 = sort { $a <=> $b } keys %buckets2;
1636 for my $key (@keys2) {
1637 last if $key >= $highest_key;
1638 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
1642 @keys = sort { $a <=> $b } keys %buckets;
1646 for my $key (@keys) {
1647 my @cps = @{$buckets{$key}};
1649 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
1651 for my $copyid (@cps) {
1653 next if $seen{$copyid};
1654 $seen{$copyid} = 1; # there could be dupes given the merged buckets
1655 my $copy = $e->retrieve_asset_copy($copyid);
1656 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
1658 unless($title) { # grab the title if we don't already have it
1659 my $vol = $e->retrieve_asset_call_number(
1660 [ $copy->call_number, { flesh => 1, flesh_fields => { acn => ['record'] } } ] );
1661 $title = $vol->record;
1664 my @status = verify_copy_for_hold(
1665 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
1667 return @status if $status[0];
1675 sub _check_volume_hold_is_possible {
1676 my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
1677 my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
1678 my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
1679 $logger->info("checking possibility of volume hold for volume ".$vol->id);
1680 for my $copy ( @$copies ) {
1681 my @status = verify_copy_for_hold(
1682 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
1683 return @status if $status[0];
1690 sub verify_copy_for_hold {
1691 my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib ) = @_;
1692 $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
1693 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
1694 { patron => $patron,
1695 requestor => $requestor,
1698 title_descriptor => $title->fixed_fields, # this is fleshed into the title object
1699 pickup_lib => $pickup_lib,
1700 request_lib => $request_lib,
1708 ($copy->circ_lib == $pickup_lib) and
1709 ($copy->status == OILS_COPY_STATUS_AVAILABLE)
1716 sub find_nearest_permitted_hold {
1719 my $editor = shift; # CStoreEditor object
1720 my $copy = shift; # copy to target
1721 my $user = shift; # staff
1722 my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
1723 my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
1725 my $bc = $copy->barcode;
1727 # find any existing holds that already target this copy
1728 my $old_holds = $editor->search_action_hold_request(
1729 { current_copy => $copy->id,
1730 cancel_time => undef,
1731 capture_time => undef
1735 # hold->type "R" means we need this copy
1736 for my $h (@$old_holds) { return ($h) if $h->hold_type eq 'R'; }
1739 my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
1741 $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
1742 " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
1744 # search for what should be the best holds for this copy to fulfill
1745 my $best_holds = $U->storagereq(
1746 "open-ils.storage.action.hold_request.nearest_hold.atomic",
1747 $user->ws_ou, $copy->id, 10, $hold_stall_interval );
1749 unless(@$best_holds) {
1751 if( my $hold = $$old_holds[0] ) {
1752 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
1756 $logger->info("circulator: no suitable holds found for copy $bc");
1757 return (undef, $evt);
1763 # for each potential hold, we have to run the permit script
1764 # to make sure the hold is actually permitted.
1765 for my $holdid (@$best_holds) {
1766 next unless $holdid;
1767 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
1769 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
1770 my $reqr = $editor->retrieve_actor_user($hold->requestor) or next;
1771 my $rlib = $editor->retrieve_actor_org_unit($hold->request_lib) or next;
1773 # see if this hold is permitted
1774 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
1775 { patron_id => $hold->usr,
1778 pickup_lib => $hold->pickup_lib,
1779 request_lib => $rlib,
1790 unless( $best_hold ) { # no "good" permitted holds were found
1791 if( my $hold = $$old_holds[0] ) { # can we return a pre-targeted hold?
1792 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
1797 $logger->info("circulator: no suitable holds found for copy $bc");
1798 return (undef, $evt);
1801 $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
1803 # indicate a permitted hold was found
1804 return $best_hold if $check_only;
1806 # we've found a permitted hold. we need to "grab" the copy
1807 # to prevent re-targeted holds (next part) from re-grabbing the copy
1808 $best_hold->current_copy($copy->id);
1809 $editor->update_action_hold_request($best_hold)
1810 or return (undef, $editor->event);
1815 # re-target any other holds that already target this copy
1816 for my $old_hold (@$old_holds) {
1817 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
1818 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
1819 $old_hold->id." after a better hold [".$best_hold->id."] was found");
1820 $old_hold->clear_current_copy;
1821 $old_hold->clear_prev_check_time;
1822 $editor->update_action_hold_request($old_hold)
1823 or return (undef, $editor->event);
1824 push(@retarget, $old_hold->id);
1827 return ($best_hold, undef, (@retarget) ? \@retarget : undef);
1835 __PACKAGE__->register_method(
1836 method => 'all_rec_holds',
1837 api_name => 'open-ils.circ.holds.retrieve_all_from_title',
1841 my( $self, $conn, $auth, $title_id, $args ) = @_;
1843 my $e = new_editor(authtoken=>$auth);
1844 $e->checkauth or return $e->event;
1845 $e->allowed('VIEW_HOLD') or return $e->event;
1848 $args->{fulfillment_time} = undef; # we don't want to see old fulfilled holds
1849 $args->{cancel_time} = undef;
1851 my $resp = { volume_holds => [], copy_holds => [], metarecord_holds => [] };
1853 my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
1855 $resp->{metarecord_holds} = $e->search_action_hold_request(
1856 { hold_type => OILS_HOLD_TYPE_METARECORD,
1857 target => $mr_map->metarecord,
1863 $resp->{title_holds} = $e->search_action_hold_request(
1865 hold_type => OILS_HOLD_TYPE_TITLE,
1866 target => $title_id,
1870 my $vols = $e->search_asset_call_number(
1871 { record => $title_id, deleted => 'f' }, {idlist=>1});
1873 return $resp unless @$vols;
1875 $resp->{volume_holds} = $e->search_action_hold_request(
1877 hold_type => OILS_HOLD_TYPE_VOLUME,
1882 my $copies = $e->search_asset_copy(
1883 { call_number => $vols, deleted => 'f' }, {idlist=>1});
1885 return $resp unless @$copies;
1887 $resp->{copy_holds} = $e->search_action_hold_request(
1889 hold_type => OILS_HOLD_TYPE_COPY,
1901 __PACKAGE__->register_method(
1902 method => 'uber_hold',
1904 api_name => 'open-ils.circ.hold.details.retrieve'
1908 my($self, $client, $auth, $hold_id) = @_;
1909 my $e = new_editor(authtoken=>$auth);
1910 $e->checkauth or return $e->event;
1911 return uber_hold_impl($e, $hold_id);
1914 __PACKAGE__->register_method(
1915 method => 'batch_uber_hold',
1918 api_name => 'open-ils.circ.hold.details.batch.retrieve'
1921 sub batch_uber_hold {
1922 my($self, $client, $auth, $hold_ids) = @_;
1923 my $e = new_editor(authtoken=>$auth);
1924 $e->checkauth or return $e->event;
1925 $client->respond(uber_hold_impl($e, $_)) for @$hold_ids;
1929 sub uber_hold_impl {
1930 my($e, $hold_id) = @_;
1934 my $hold = $e->retrieve_action_hold_request(
1939 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
1942 ) or return $e->event;
1944 if($hold->usr->id ne $e->requestor->id) {
1945 # A user is allowed to see his/her own holds
1946 $e->allowed('VIEW_HOLD') or return $e->event;
1949 my $user = $hold->usr;
1950 $hold->usr($user->id);
1952 my $card = $e->retrieve_actor_card($user->card)
1953 or return $e->event;
1955 my( $mvr, $volume, $copy ) = find_hold_mvr($e, $hold);
1957 flesh_hold_notices([$hold], $e);
1958 flesh_hold_transits([$hold]);
1960 my $details = retrieve_hold_queue_status_impl($e, $hold);
1967 patron_first => $user->first_given_name,
1968 patron_last => $user->family_name,
1969 patron_barcode => $card->barcode,
1976 # -----------------------------------------------------
1977 # Returns the MVR object that represents what the
1979 # -----------------------------------------------------
1981 my( $e, $hold ) = @_;
1987 if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
1988 my $mr = $e->retrieve_metabib_metarecord($hold->target)
1989 or return $e->event;
1990 $tid = $mr->master_record;
1992 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
1993 $tid = $hold->target;
1995 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
1996 $volume = $e->retrieve_asset_call_number($hold->target)
1997 or return $e->event;
1998 $tid = $volume->record;
2000 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_COPY ) {
2001 $copy = $e->retrieve_asset_copy($hold->target)
2002 or return $e->event;
2003 $volume = $e->retrieve_asset_call_number($copy->call_number)
2004 or return $e->event;
2005 $tid = $volume->record;
2008 if(!$copy and ref $hold->current_copy ) {
2009 $copy = $hold->current_copy;
2010 $hold->current_copy($copy->id);
2013 if(!$volume and $copy) {
2014 $volume = $e->retrieve_asset_call_number($copy->call_number);
2017 # TODO return metarcord mvr for M holds
2018 my $title = $e->retrieve_biblio_record_entry($tid);
2019 return ( $U->record_to_mvr($title), $volume, $copy );
2023 __PACKAGE__->register_method(
2024 method => 'clear_shelf_process',
2026 api_name => 'open-ils.circ.hold.clear_shelf.process',
2029 1. Find all holds that have expired on the holds shelf
2031 3. If a clear-shelf status is configured, put targeted copies into this status
2032 4. Divide copies into 3 groups: items to transit, items to reshelve, and items
2033 that are needed for holds. No subsequent action is taken on the holds
2034 or items after grouping.
2039 sub clear_shelf_process {
2040 my($self, $client, $auth, $org_id) = @_;
2042 my $e = new_editor(authtoken=>$auth, xact => 1);
2043 $e->checkauth or return $e->die_event;
2045 $org_id ||= $e->requestor->ws_ou;
2046 $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
2048 my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
2050 # Find holds on the shelf that have been there too long
2051 my $hold_ids = $e->search_action_hold_request(
2052 { shelf_expire_time => {'<' => 'now'},
2053 pickup_lib => $org_id,
2054 cancel_time => undef,
2055 fulfillment_time => undef,
2056 shelf_time => {'!=' => undef}
2063 for my $hold_id (@$hold_ids) {
2065 $logger->info("Clear shelf processing hold $hold_id");
2067 my $hold = $e->retrieve_action_hold_request([
2070 flesh_fields => {ahr => ['current_copy']}
2074 $hold->cancel_time('now');
2075 $hold->cancel_cause(2); # Hold Shelf expiration
2076 $e->update_action_hold_request($hold) or return $e->die_event;
2078 my $copy = $hold->current_copy;
2081 # if a clear-shelf copy status is defined, update the copy
2082 $copy->status($copy_status);
2083 $copy->edit_date('now');
2084 $copy->editor($e->requestor->id);
2085 $e->update_asset_copy($copy) or return $e->die_event;
2088 my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
2092 # copy is needed for a hold
2093 $client->respond({action => 'hold', copy => $copy, hold_id => $hold->id});
2095 } elsif($copy->circ_lib != $e->requestor->ws_ou) {
2097 # copy needs to transit
2098 $client->respond({action => 'transit', copy => $copy, hold_id => $hold->id});
2102 # copy needs to go back to the shelf
2103 $client->respond({action => 'shelf', copy => $copy, hold_id => $hold->id});
2106 push(@holds, $hold);
2111 # tell the client we're done
2112 $client->resopnd_complete;
2114 # fire off the hold cancelation trigger
2115 my $trigger = OpenSRF::AppSession->connect('open-ils.trigger');
2117 for my $hold (@holds) {
2119 my $req = $trigger->request(
2120 'open-ils.trigger.event.autocreate',
2121 'hold_request.cancel.expire_holds_shelf',
2124 # wait for response so don't flood the service
2128 $trigger->disconnect;
2132 __PACKAGE__->register_method(
2133 method => 'usr_hold_summary',
2134 api_name => 'open-ils.circ.holds.user_summary',
2136 Returns a summary of holds statuses for a given user
2140 sub usr_hold_summary {
2141 my($self, $conn, $auth, $user_id) = @_;
2143 my $e = new_editor(authtoken=>$auth);
2144 $e->checkauth or return $e->event;
2145 $e->allowed('VIEW_HOLD') or return $e->event;
2147 my $holds = $e->search_action_hold_request(
2150 fulfillment_time => undef,
2151 cancel_time => undef,
2155 my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
2156 $summary{_hold_status($e, $_)} += 1 for @$holds;