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";
41 __PACKAGE__->register_method(
42 method => "create_hold_batch",
43 api_name => "open-ils.circ.holds.create.batch",
46 desc => q/@see open-ils.circ.holds.create.batch/,
48 { desc => 'Authentication token', type => 'string' },
49 { desc => 'Array of hold objects', type => 'array' }
52 desc => 'Array of hold ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
57 __PACKAGE__->register_method(
58 method => "create_hold_batch",
59 api_name => "open-ils.circ.holds.create.override.batch",
62 desc => '@see open-ils.circ.holds.create.batch',
67 sub create_hold_batch {
68 my( $self, $conn, $auth, $hold_list ) = @_;
69 (my $method = $self->api_name) =~ s/\.batch//og;
70 foreach (@$hold_list) {
71 my ($res) = $self->method_lookup($method)->run($auth, $_);
78 __PACKAGE__->register_method(
79 method => "create_hold",
80 api_name => "open-ils.circ.holds.create",
82 desc => "Create a new hold for an item. From a permissions perspective, " .
83 "the login session is used as the 'requestor' of the hold. " .
84 "The hold recipient is determined by the 'usr' setting within the hold object. " .
85 'First we verify the requestor has holds request permissions. ' .
86 'Then we verify that the recipient is allowed to make the given hold. ' .
87 'If not, we see if the requestor has "override" capabilities. If not, ' .
88 'a permission exception is returned. If permissions allow, we cycle ' .
89 'through the set of holds objects and create. ' .
90 'If the recipient does not have permission to place multiple holds ' .
91 'on a single title and said operation is attempted, a permission ' .
92 'exception is returned',
94 { desc => 'Authentication token', type => 'string' },
95 { desc => 'Hold object for hold to be created', type => 'object' }
98 desc => 'Undef on success, -1 on missing arg, event (or ref to array of events) on error(s)',
103 __PACKAGE__->register_method(
104 method => "create_hold",
105 api_name => "open-ils.circ.holds.create.override",
106 notes => '@see open-ils.circ.holds.create',
108 desc => "If the recipient is not allowed to receive the requested hold, " .
109 "call this method to attempt the override",
111 { desc => 'Authentication token', type => 'string' },
112 { desc => 'Hold object for hold to be created', type => 'object' }
115 desc => 'Undef on success, -1 on missing arg, event (or ref to array of events) on error(s)',
121 my( $self, $conn, $auth, $hold ) = @_;
122 return -1 unless $hold;
123 my $e = new_editor(authtoken=>$auth, xact=>1);
124 return $e->die_event unless $e->checkauth;
126 my $override = 1 if $self->api_name =~ /override/;
130 my $requestor = $e->requestor;
131 my $recipient = $requestor;
133 if( $requestor->id ne $hold->usr ) {
134 # Make sure the requestor is allowed to place holds for
135 # the recipient if they are not the same people
136 $recipient = $e->retrieve_actor_user($hold->usr) or return $e->die_event;
137 $e->allowed('REQUEST_HOLDS', $recipient->home_ou) or return $e->die_event;
140 # If the related org setting tells us to, block if patron privs have expired
141 my $expire_setting = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_BLOCK_HOLD_FOR_EXPIRED_PATRON);
142 if ($expire_setting) {
143 my $expire = DateTime::Format::ISO8601->new->parse_datetime(
144 cleanse_ISO8601($recipient->expire_date));
146 push( @events, OpenILS::Event->new(
147 'PATRON_ACCOUNT_EXPIRED',
148 "payload" => {"fail_part" => "actor.usr.privs_expired"}
149 )) if( CORE::time > $expire->epoch ) ;
152 # Now make sure the recipient is allowed to receive the specified hold
153 my $porg = $recipient->home_ou;
154 my $rid = $e->requestor->id;
155 my $t = $hold->hold_type;
157 # See if a duplicate hold already exists
159 usr => $recipient->id,
161 fulfillment_time => undef,
162 target => $hold->target,
163 cancel_time => undef,
166 $sargs->{holdable_formats} = $hold->holdable_formats if $t eq 'M';
168 my $existing = $e->search_action_hold_request($sargs);
169 push( @events, OpenILS::Event->new('HOLD_EXISTS')) if @$existing;
171 my $checked_out = hold_item_is_checked_out($e, $recipient->id, $hold->hold_type, $hold->target);
172 push( @events, OpenILS::Event->new('HOLD_ITEM_CHECKED_OUT')) if $checked_out;
174 if ( $t eq OILS_HOLD_TYPE_METARECORD ) {
175 return $e->die_event unless $e->allowed('MR_HOLDS', $porg);
176 } elsif ( $t eq OILS_HOLD_TYPE_TITLE ) {
177 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
178 } elsif ( $t eq OILS_HOLD_TYPE_VOLUME ) {
179 return $e->die_event unless $e->allowed('VOLUME_HOLDS', $porg);
180 } elsif ( $t eq OILS_HOLD_TYPE_ISSUANCE ) {
181 return $e->die_event unless $e->allowed('ISSUANCE_HOLDS', $porg);
182 } elsif ( $t eq OILS_HOLD_TYPE_COPY ) {
183 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
184 } elsif ( $t eq OILS_HOLD_TYPE_FORCE ) {
185 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
186 } elsif ( $t eq OILS_HOLD_TYPE_RECALL ) {
187 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
195 for my $evt (@events) {
197 my $name = $evt->{textcode};
198 return $e->die_event unless $e->allowed("$name.override", $porg);
202 # set the configured expire time
203 unless($hold->expire_time) {
204 my $interval = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_HOLD_EXPIRE);
206 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
207 $hold->expire_time($U->epoch2ISO8601($date->epoch));
211 $hold->requestor($e->requestor->id);
212 $hold->request_lib($e->requestor->ws_ou);
213 $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
214 $hold = $e->create_action_hold_request($hold) or return $e->die_event;
218 $conn->respond_complete($hold->id);
221 'open-ils.storage.action.hold_request.copy_targeter',
222 undef, $hold->id ) unless $U->is_true($hold->frozen);
227 # makes sure that a user has permission to place the type of requested hold
228 # returns the Perm exception if not allowed, returns undef if all is well
229 sub _check_holds_perm {
230 my($type, $user_id, $org_id) = @_;
234 $evt = $apputils->check_perms($user_id, $org_id, "MR_HOLDS" );
235 } elsif ($type eq "T") {
236 $evt = $apputils->check_perms($user_id, $org_id, "TITLE_HOLDS" );
237 } elsif($type eq "V") {
238 $evt = $apputils->check_perms($user_id, $org_id, "VOLUME_HOLDS");
239 } elsif($type eq "C") {
240 $evt = $apputils->check_perms($user_id, $org_id, "COPY_HOLDS" );
247 # tests if the given user is allowed to place holds on another's behalf
248 sub _check_request_holds_perm {
251 if (my $evt = $apputils->check_perms(
252 $user_id, $org_id, "REQUEST_HOLDS")) {
257 my $ses_is_req_note = 'The login session is the requestor. If the requestor is different from the user, ' .
258 'then the requestor must have VIEW_HOLD permissions';
260 __PACKAGE__->register_method(
261 method => "retrieve_holds_by_id",
262 api_name => "open-ils.circ.holds.retrieve_by_id",
264 desc => "Retrieve the hold, with hold transits attached, for the specified ID. $ses_is_req_note",
266 { desc => 'Authentication token', type => 'string' },
267 { desc => 'Hold ID', type => 'number' }
270 desc => 'Hold object with transits attached, event on error',
276 sub retrieve_holds_by_id {
277 my($self, $client, $auth, $hold_id) = @_;
278 my $e = new_editor(authtoken=>$auth);
279 $e->checkauth or return $e->event;
280 $e->allowed('VIEW_HOLD') or return $e->event;
282 my $holds = $e->search_action_hold_request(
284 { id => $hold_id , fulfillment_time => undef },
286 order_by => { ahr => "request_time" },
288 flesh_fields => {ahr => ['notes']}
293 flesh_hold_transits($holds);
294 flesh_hold_notices($holds, $e);
299 __PACKAGE__->register_method(
300 method => "retrieve_holds",
301 api_name => "open-ils.circ.holds.retrieve",
303 desc => "Retrieves all the holds, with hold transits attached, for the specified user. $ses_is_req_note",
305 { desc => 'Authentication token', type => 'string' },
306 { desc => 'User ID', type => 'integer' }
309 desc => 'list of holds, event on error',
314 __PACKAGE__->register_method(
315 method => "retrieve_holds",
316 api_name => "open-ils.circ.holds.id_list.retrieve",
319 desc => "Retrieves all the hold IDs, for the specified user. $ses_is_req_note",
321 { desc => 'Authentication token', type => 'string' },
322 { desc => 'User ID', type => 'integer' }
325 desc => 'list of holds, event on error',
330 __PACKAGE__->register_method(
331 method => "retrieve_holds",
332 api_name => "open-ils.circ.holds.canceled.retrieve",
335 desc => "Retrieves all the cancelled holds for the specified user. $ses_is_req_note",
337 { desc => 'Authentication token', type => 'string' },
338 { desc => 'User ID', type => 'integer' }
341 desc => 'list of holds, event on error',
346 __PACKAGE__->register_method(
347 method => "retrieve_holds",
348 api_name => "open-ils.circ.holds.canceled.id_list.retrieve",
351 desc => "Retrieves list of cancelled hold IDs for the specified user. $ses_is_req_note",
353 { desc => 'Authentication token', type => 'string' },
354 { desc => 'User ID', type => 'integer' }
357 desc => 'list of hold IDs, event on error',
364 my ($self, $client, $auth, $user_id) = @_;
366 my $e = new_editor(authtoken=>$auth);
367 return $e->event unless $e->checkauth;
368 $user_id = $e->requestor->id unless defined $user_id;
370 my $notes_filter = {staff => 'f'};
371 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
372 unless($user_id == $e->requestor->id) {
373 if($e->allowed('VIEW_HOLD', $user->home_ou)) {
374 $notes_filter = {staff => 't'}
376 my $allowed = OpenILS::Application::Actor::Friends->friend_perm_allowed(
377 $e, $user_id, $e->requestor->id, 'hold.view');
378 return $e->event unless $allowed;
381 # staff member looking at his/her own holds can see staff and non-staff notes
382 $notes_filter = {} if $e->allowed('VIEW_HOLD', $user->home_ou);
387 if($self->api_name !~ /canceled/) {
389 # Fetch the active holds
391 $holds = $e->search_action_hold_request([
393 fulfillment_time => undef,
394 cancel_time => undef,
396 {order_by => {ahr => "request_time"}}
401 # Fetch the canceled holds
404 my $cancel_count = $U->ou_ancestor_setting_value(
405 $e->requestor->ws_ou, 'circ.holds.canceled.display_count', $e);
407 unless($cancel_count) {
408 $cancel_age = $U->ou_ancestor_setting_value(
409 $e->requestor->ws_ou, 'circ.holds.canceled.display_age', $e);
412 if($cancel_count) { # limit by count
414 # find at most cancel_count canceled holds
415 $holds = $e->search_action_hold_request([
417 fulfillment_time => undef,
418 cancel_time => {'!=' => undef},
420 {order_by => {ahr => "cancel_time desc"}, limit => $cancel_count}
423 } elsif($cancel_age) { # limit by age
425 # find all of the canceled holds that were canceled within the configured time frame
426 my $date = DateTime->now->subtract(seconds => OpenSRF::Utils::interval_to_seconds($cancel_age));
427 $date = $U->epoch2ISO8601($date->epoch);
429 $holds = $e->search_action_hold_request([
431 fulfillment_time => undef,
432 cancel_time => {'>=' => $date},
434 {order_by => {ahr => "cancel_time desc"}}
439 if( $self->api_name !~ /id_list/ ) {
440 for my $hold ( @$holds ) {
441 $hold->notes($e->search_action_hold_request_note({hold => $hold->id, %$notes_filter}));
443 $e->search_action_hold_transit_copy([
445 {order_by => {ahtc => 'id desc'}, limit => 1}])->[0]
451 return [ map { $_->id } @$holds ];
455 __PACKAGE__->register_method(
456 method => 'user_hold_count',
457 api_name => 'open-ils.circ.hold.user.count'
460 sub user_hold_count {
461 my ( $self, $conn, $auth, $userid ) = @_;
462 my $e = new_editor( authtoken => $auth );
463 return $e->event unless $e->checkauth;
464 my $patron = $e->retrieve_actor_user($userid)
466 return $e->event unless $e->allowed( 'VIEW_HOLD', $patron->home_ou );
467 return __user_hold_count( $self, $e, $userid );
470 sub __user_hold_count {
471 my ( $self, $e, $userid ) = @_;
472 my $holds = $e->search_action_hold_request(
475 fulfillment_time => undef,
476 cancel_time => undef,
481 return scalar(@$holds);
485 __PACKAGE__->register_method(
486 method => "retrieve_holds_by_pickup_lib",
487 api_name => "open-ils.circ.holds.retrieve_by_pickup_lib",
489 "Retrieves all the holds, with hold transits attached, for the specified pickup_ou id."
492 __PACKAGE__->register_method(
493 method => "retrieve_holds_by_pickup_lib",
494 api_name => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
495 notes => "Retrieves all the hold ids for the specified pickup_ou id. "
498 sub retrieve_holds_by_pickup_lib {
499 my ($self, $client, $login_session, $ou_id) = @_;
501 #FIXME -- put an appropriate permission check here
502 #my( $user, $target, $evt ) = $apputils->checkses_requestor(
503 # $login_session, $user_id, 'VIEW_HOLD' );
504 #return $evt if $evt;
506 my $holds = $apputils->simplereq(
508 "open-ils.cstore.direct.action.hold_request.search.atomic",
510 pickup_lib => $ou_id ,
511 fulfillment_time => undef,
514 { order_by => { ahr => "request_time" } }
517 if ( ! $self->api_name =~ /id_list/ ) {
518 flesh_hold_transits($holds);
522 return [ map { $_->id } @$holds ];
526 __PACKAGE__->register_method(
527 method => "uncancel_hold",
528 api_name => "open-ils.circ.hold.uncancel"
532 my($self, $client, $auth, $hold_id) = @_;
533 my $e = new_editor(authtoken=>$auth, xact=>1);
534 return $e->die_event unless $e->checkauth;
536 my $hold = $e->retrieve_action_hold_request($hold_id)
537 or return $e->die_event;
538 return $e->die_event unless $e->allowed('CANCEL_HOLDS', $hold->request_lib);
540 if ($hold->fulfillment_time) {
544 unless ($hold->cancel_time) {
549 # if configured to reset the request time, also reset the expire time
550 if($U->ou_ancestor_setting_value(
551 $hold->request_lib, 'circ.holds.uncancel.reset_request_time', $e)) {
553 $hold->request_time('now');
554 my $interval = $U->ou_ancestor_setting_value($hold->request_lib, OILS_SETTING_HOLD_EXPIRE);
556 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
557 $hold->expire_time($U->epoch2ISO8601($date->epoch));
561 $hold->clear_cancel_time;
562 $hold->clear_cancel_cause;
563 $hold->clear_cancel_note;
564 $e->update_action_hold_request($hold) or return $e->die_event;
567 $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
573 __PACKAGE__->register_method(
574 method => "cancel_hold",
575 api_name => "open-ils.circ.hold.cancel",
577 desc => 'Cancels the specified hold. The login session is the requestor. If the requestor is different from the usr field ' .
578 'on the hold, the requestor must have CANCEL_HOLDS permissions. The hold may be either the hold object or the hold id',
580 {desc => 'Authentication token', type => 'string'},
581 {desc => 'Hold ID', type => 'number'},
582 {desc => 'Cause of Cancellation', type => 'string'},
583 {desc => 'Note', type => 'string'}
586 desc => '1 on success, event on error'
592 my($self, $client, $auth, $holdid, $cause, $note) = @_;
594 my $e = new_editor(authtoken=>$auth, xact=>1);
595 return $e->die_event unless $e->checkauth;
597 my $hold = $e->retrieve_action_hold_request($holdid)
598 or return $e->die_event;
600 if( $e->requestor->id ne $hold->usr ) {
601 return $e->die_event unless $e->allowed('CANCEL_HOLDS');
604 if ($hold->cancel_time) {
609 # If the hold is captured, reset the copy status
610 if( $hold->capture_time and $hold->current_copy ) {
612 my $copy = $e->retrieve_asset_copy($hold->current_copy)
613 or return $e->die_event;
615 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
616 $logger->info("canceling hold $holdid whose item is on the holds shelf");
617 # $logger->info("setting copy to status 'reshelving' on hold cancel");
618 # $copy->status(OILS_COPY_STATUS_RESHELVING);
619 # $copy->editor($e->requestor->id);
620 # $copy->edit_date('now');
621 # $e->update_asset_copy($copy) or return $e->event;
623 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
626 $logger->warn("! canceling hold [$hid] that is in transit");
627 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
630 my $trans = $e->retrieve_action_transit_copy($transid);
631 # Leave the transit alive, but set the copy status to
632 # reshelving so it will be properly reshelved when it gets back home
634 $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
635 $e->update_action_transit_copy($trans) or return $e->die_event;
641 $hold->cancel_time('now');
642 $hold->cancel_cause($cause);
643 $hold->cancel_note($note);
644 $e->update_action_hold_request($hold)
645 or return $e->die_event;
647 delete_hold_copy_maps($self, $e, $hold->id);
651 $U->create_events_for_hook('hold_request.cancel.staff', $hold, $hold->pickup_lib)
652 if $e->requestor->id != $hold->usr;
657 sub delete_hold_copy_maps {
662 my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
664 $editor->delete_action_hold_copy_map($_)
665 or return $editor->event;
671 my $update_hold_desc = 'The login session is the requestor. ' .
672 'If the requestor is different from the usr field on the hold, ' .
673 'the requestor must have UPDATE_HOLDS permissions. ' .
674 'If supplying a hash of hold data, "id" must be included. ' .
675 'The hash is ignored if a hold object is supplied, ' .
676 'so you should supply only one kind of hold data argument.' ;
678 __PACKAGE__->register_method(
679 method => "update_hold",
680 api_name => "open-ils.circ.hold.update",
682 desc => "Updates the specified hold. $update_hold_desc",
684 {desc => 'Authentication token', type => 'string'},
685 {desc => 'Hold Object', type => 'object'},
686 {desc => 'Hash of values to be applied', type => 'object'}
689 desc => 'Hold ID on success, event on error',
695 __PACKAGE__->register_method(
696 method => "batch_update_hold",
697 api_name => "open-ils.circ.hold.update.batch",
700 desc => "Updates the specified hold(s). $update_hold_desc",
702 {desc => 'Authentication token', type => 'string'},
703 {desc => 'Array of hold obejcts', type => 'array' },
704 {desc => 'Array of hashes of values to be applied', type => 'array' }
707 desc => 'Hold ID per success, event per error',
713 my($self, $client, $auth, $hold, $values) = @_;
714 my $e = new_editor(authtoken=>$auth, xact=>1);
715 return $e->die_event unless $e->checkauth;
716 my $resp = update_hold_impl($self, $e, $hold, $values);
717 if ($U->event_code($resp)) {
721 $e->commit; # FIXME: update_hold_impl already does $e->commit ??
725 sub batch_update_hold {
726 my($self, $client, $auth, $hold_list, $values_list) = @_;
727 my $e = new_editor(authtoken=>$auth);
728 return $e->die_event unless $e->checkauth;
730 my $count = ($hold_list) ? scalar(@$hold_list) : scalar(@$values_list); # FIXME: we don't know for sure that we got $values_list. we could have neither list.
732 $values_list ||= []; # FIXME: either move this above $count declaration, or send an event if both lists undef. Probably the latter.
734 # FIXME: Failing over to [] guarantees warnings for "Use of unitialized value" in update_hold_impl call.
735 # FIXME: We should be sure we only call update_hold_impl with hold object OR hash, not both.
737 for my $idx (0..$count-1) {
739 my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
740 $e->xact_commit unless $U->event_code($resp);
741 $client->respond($resp);
745 return undef; # not in the register return type, assuming we should always have at least one list populated
748 sub update_hold_impl {
749 my($self, $e, $hold, $values) = @_;
752 $hold = $e->retrieve_action_hold_request($values->{id})
753 or return $e->die_event;
754 for my $k (keys %$values) {
755 if (defined $values->{$k}) {
756 $hold->$k($values->{$k});
758 my $f = "clear_$k"; $hold->$f();
763 my $orig_hold = $e->retrieve_action_hold_request($hold->id)
764 or return $e->die_event;
766 # don't allow the user to be changed
767 return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
769 if($hold->usr ne $e->requestor->id) {
770 # if the hold is for a different user, make sure the
771 # requestor has the appropriate permissions
772 my $usr = $e->retrieve_actor_user($hold->usr)
773 or return $e->die_event;
774 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
778 # --------------------------------------------------------------
779 # Changing the request time is like playing God
780 # --------------------------------------------------------------
781 if($hold->request_time ne $orig_hold->request_time) {
782 return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
783 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
786 # --------------------------------------------------------------
787 # if the hold is on the holds shelf or in transit and the pickup
788 # lib changes we need to create a new transit.
789 # --------------------------------------------------------------
790 if($orig_hold->pickup_lib ne $hold->pickup_lib) {
792 my $status = _hold_status($e, $hold);
794 if($status == 3) { # in transit
796 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
797 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
799 $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
801 # update the transit to reflect the new pickup location
802 my $transit = $e->search_action_hold_transit_copy(
803 {hold=>$hold->id, dest_recv_time => undef})->[0]
804 or return $e->die_event;
806 $transit->prev_dest($transit->dest); # mark the previous destination on the transit
807 $transit->dest($hold->pickup_lib);
808 $e->update_action_hold_transit_copy($transit) or return $e->die_event;
810 } elsif($status == 4) { # on holds shelf
812 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
813 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
815 $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
817 # create the new transit
818 my $evt = transit_hold($e, $orig_hold, $hold, $e->retrieve_asset_copy($hold->current_copy));
823 update_hold_if_frozen($self, $e, $hold, $orig_hold);
824 $e->update_action_hold_request($hold) or return $e->die_event;
827 # a change to mint-condition changes the set of potential copies, so retarget the hold;
828 if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
829 _reset_hold($self, $e->requestor, $hold)
836 my($e, $orig_hold, $hold, $copy) = @_;
837 my $src = $orig_hold->pickup_lib;
838 my $dest = $hold->pickup_lib;
840 $logger->info("putting hold into transit on pickup_lib update");
842 my $transit = Fieldmapper::action::hold_transit_copy->new;
843 $transit->hold($hold->id);
844 $transit->source($src);
845 $transit->dest($dest);
846 $transit->target_copy($copy->id);
847 $transit->source_send_time('now');
848 $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
850 $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
851 $copy->editor($e->requestor->id);
852 $copy->edit_date('now');
854 $e->create_action_hold_transit_copy($transit) or return $e->die_event;
855 $e->update_asset_copy($copy) or return $e->die_event;
859 # if the hold is frozen, this method ensures that the hold is not "targeted",
860 # that is, it clears the current_copy and prev_check_time to essentiallly
861 # reset the hold. If it is being activated, it runs the targeter in the background
862 sub update_hold_if_frozen {
863 my($self, $e, $hold, $orig_hold) = @_;
864 return if $hold->capture_time;
866 if($U->is_true($hold->frozen)) {
867 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
868 $hold->clear_current_copy;
869 $hold->clear_prev_check_time;
872 if($U->is_true($orig_hold->frozen)) {
873 $logger->info("Running targeter on activated hold ".$hold->id);
874 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
879 __PACKAGE__->register_method(
880 method => "hold_note_CUD",
881 api_name => "open-ils.circ.hold_request.note.cud",
883 desc => 'Create, update or delete a hold request note. If the operator (from Auth. token) '
884 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
886 { desc => 'Authentication token', type => 'string' },
887 { desc => 'Hold note object', type => 'object' }
890 desc => 'Returns the note ID, event on error'
896 my($self, $conn, $auth, $note) = @_;
898 my $e = new_editor(authtoken => $auth, xact => 1);
899 return $e->die_event unless $e->checkauth;
901 my $hold = $e->retrieve_action_hold_request($note->hold)
902 or return $e->die_event;
904 if($hold->usr ne $e->requestor->id) {
905 my $usr = $e->retrieve_actor_user($hold->usr);
906 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
907 $note->staff('t') if $note->isnew;
911 $e->create_action_hold_request_note($note) or return $e->die_event;
912 } elsif($note->ischanged) {
913 $e->update_action_hold_request_note($note) or return $e->die_event;
914 } elsif($note->isdeleted) {
915 $e->delete_action_hold_request_note($note) or return $e->die_event;
923 __PACKAGE__->register_method(
924 method => "retrieve_hold_status",
925 api_name => "open-ils.circ.hold.status.retrieve",
927 desc => 'Calculates the current status of the hold. The requestor must have ' .
928 'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
930 { desc => 'Hold ID', type => 'number' }
933 # type => 'number', # event sometimes
934 desc => <<'END_OF_DESC'
935 Returns event on error or:
936 -1 on error (for now),
937 1 for 'waiting for copy to become available',
938 2 for 'waiting for copy capture',
941 5 for 'hold-shelf-delay'
948 sub retrieve_hold_status {
949 my($self, $client, $auth, $hold_id) = @_;
951 my $e = new_editor(authtoken => $auth);
952 return $e->event unless $e->checkauth;
953 my $hold = $e->retrieve_action_hold_request($hold_id)
956 if( $e->requestor->id != $hold->usr ) {
957 return $e->event unless $e->allowed('VIEW_HOLD');
960 return _hold_status($e, $hold);
966 if ($hold->cancel_time) {
969 return 1 unless $hold->current_copy;
970 return 2 unless $hold->capture_time;
972 my $copy = $hold->current_copy;
973 unless( ref $copy ) {
974 $copy = $e->retrieve_asset_copy($hold->current_copy)
978 return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
980 if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
982 my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
983 return 4 unless $hs_wait_interval;
985 # if a hold_shelf_status_delay interval is defined and start_time plus
986 # the interval is greater than now, consider the hold to be in the virtual
987 # "on its way to the holds shelf" status. Return 5.
989 my $transit = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
990 my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
991 $start_time = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
992 my $end_time = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
994 return 5 if $end_time > DateTime->now;
1003 __PACKAGE__->register_method(
1004 method => "retrieve_hold_queue_stats",
1005 api_name => "open-ils.circ.hold.queue_stats.retrieve",
1007 desc => 'Returns summary data about the state of a hold',
1009 { desc => 'Authentication token', type => 'string'},
1010 { desc => 'Hold ID', type => 'number'},
1013 desc => q/Summary object with keys:
1014 total_holds : total holds in queue
1015 queue_position : current queue position
1016 potential_copies : number of potential copies for this hold
1017 estimated_wait : estimated wait time in days
1018 status : hold status
1019 -1 => error or unexpected state,
1020 1 => 'waiting for copy to become available',
1021 2 => 'waiting for copy capture',
1024 5 => 'hold-shelf-delay'
1031 sub retrieve_hold_queue_stats {
1032 my($self, $conn, $auth, $hold_id) = @_;
1033 my $e = new_editor(authtoken => $auth);
1034 return $e->event unless $e->checkauth;
1035 my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1036 if($e->requestor->id != $hold->usr) {
1037 return $e->event unless $e->allowed('VIEW_HOLD');
1039 return retrieve_hold_queue_status_impl($e, $hold);
1042 sub retrieve_hold_queue_status_impl {
1046 # The holds queue is defined as the distinct set of holds that share at
1047 # least one potential copy with the context hold, plus any holds that
1048 # share the same hold type and target. The latter part exists to
1049 # accomodate holds that currently have no potential copies
1050 my $q_holds = $e->json_query({
1052 # fetch cut_in_line and request_time since they're in the order_by
1053 # and we're asking for distinct values
1054 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1055 from => { ahr => 'ahcm' },
1059 "field" => "cut_in_line",
1060 "transform" => "coalesce",
1062 "direction" => "desc"
1064 { "class" => "ahr", "field" => "request_time" }
1071 select => {ahcm => ['target_copy']},
1073 where => {hold => $hold->id}
1080 if (!@$q_holds) { # none? maybe we don't have a map ...
1081 $q_holds = $e->json_query({
1082 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1087 "field" => "cut_in_line",
1088 "transform" => "coalesce",
1090 "direction" => "desc"
1092 { "class" => "ahr", "field" => "request_time" }
1095 hold_type => $hold->hold_type,
1096 target => $hold->target
1103 for my $h (@$q_holds) {
1104 last if $h->{id} == $hold->id;
1108 my $hold_data = $e->json_query({
1110 acp => [ {column => 'id', transform => 'count', aggregate => 1, alias => 'count'} ],
1111 ccm => [ {column =>'avg_wait_time'} ]
1117 ccm => {type => 'left'}
1122 where => {'+ahcm' => {hold => $hold->id} }
1125 my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1127 my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1128 my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1129 $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1130 $default_wait ||= '0 seconds';
1132 # Estimated wait time is the average wait time across the set
1133 # of potential copies, divided by the number of potential copies
1134 # times the queue position.
1136 my $combined_secs = 0;
1137 my $num_potentials = 0;
1139 for my $wait_data (@$hold_data) {
1140 my $count += $wait_data->{count};
1141 $combined_secs += $count *
1142 OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1143 $num_potentials += $count;
1146 my $estimated_wait = -1;
1148 if($num_potentials) {
1149 my $avg_wait = $combined_secs / $num_potentials;
1150 $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1151 $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1155 total_holds => scalar(@$q_holds),
1156 queue_position => $qpos,
1157 potential_copies => $num_potentials,
1158 status => _hold_status( $e, $hold ),
1159 estimated_wait => int($estimated_wait)
1164 sub fetch_open_hold_by_current_copy {
1167 my $hold = $apputils->simplereq(
1169 'open-ils.cstore.direct.action.hold_request.search.atomic',
1170 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1171 return $hold->[0] if ref($hold);
1175 sub fetch_related_holds {
1178 return $apputils->simplereq(
1180 'open-ils.cstore.direct.action.hold_request.search.atomic',
1181 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1185 __PACKAGE__->register_method(
1186 method => "hold_pull_list",
1187 api_name => "open-ils.circ.hold_pull_list.retrieve",
1189 desc => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1190 'The location is determined by the login session.',
1192 { desc => 'Limit (optional)', type => 'number'},
1193 { desc => 'Offset (optional)', type => 'number'},
1196 desc => 'reference to a list of holds, or event on failure',
1201 __PACKAGE__->register_method(
1202 method => "hold_pull_list",
1203 api_name => "open-ils.circ.hold_pull_list.id_list.retrieve",
1205 desc => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1206 'The location is determined by the login session.',
1208 { desc => 'Limit (optional)', type => 'number'},
1209 { desc => 'Offset (optional)', type => 'number'},
1212 desc => 'reference to a list of holds, or event on failure',
1217 __PACKAGE__->register_method(
1218 method => "hold_pull_list",
1219 api_name => "open-ils.circ.hold_pull_list.retrieve.count",
1221 desc => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1222 'The location is determined by the login session.',
1224 { desc => 'Limit (optional)', type => 'number'},
1225 { desc => 'Offset (optional)', type => 'number'},
1228 desc => 'Holds count (integer), or event on failure',
1235 sub hold_pull_list {
1236 my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1237 my( $reqr, $evt ) = $U->checkses($authtoken);
1238 return $evt if $evt;
1240 my $org = $reqr->ws_ou || $reqr->home_ou;
1241 # the perm locaiton shouldn't really matter here since holds
1242 # will exist all over and VIEW_HOLDS should be universal
1243 $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1244 return $evt if $evt;
1246 if($self->api_name =~ /count/) {
1248 my $count = $U->storagereq(
1249 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1250 $org, $limit, $offset );
1252 $logger->info("Grabbing pull list for org unit $org with $count items");
1255 } elsif( $self->api_name =~ /id_list/ ) {
1256 return $U->storagereq(
1257 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1258 $org, $limit, $offset );
1261 return $U->storagereq(
1262 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1263 $org, $limit, $offset );
1267 __PACKAGE__->register_method(
1268 method => "print_hold_pull_list",
1269 api_name => "open-ils.circ.hold_pull_list.print",
1271 desc => 'Returns an HTML-formatted holds pull list',
1273 { desc => 'Authtoken', type => 'string'},
1274 { desc => 'Org unit ID. Optional, defaults to workstation org unit', type => 'number'},
1277 desc => 'HTML string',
1283 sub print_hold_pull_list {
1284 my($self, $client, $auth, $org_id) = @_;
1286 my $e = new_editor(authtoken=>$auth);
1287 return $e->event unless $e->checkauth;
1289 $org_id = (defined $org_id) ? $org_id : $e->requestor->ws_ou;
1290 return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1292 my $hold_ids = $U->storagereq(
1293 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1296 return undef unless @$hold_ids;
1298 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1300 # Holds will /NOT/ be in order after this ...
1301 my $holds = $e->search_action_hold_request({id => $hold_ids}, {substream => 1});
1302 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1304 # ... so we must resort.
1305 my $hold_map = +{map { $_->id => $_ } @$holds};
1306 my $sorted_holds = [];
1307 push @$sorted_holds, $hold_map->{$_} foreach @$hold_ids;
1309 return $U->fire_object_event(
1310 undef, "ahr.format.pull_list", $sorted_holds,
1311 $org_id, undef, undef, $client
1316 __PACKAGE__->register_method(
1317 method => "print_hold_pull_list_stream",
1319 api_name => "open-ils.circ.hold_pull_list.print.stream",
1321 desc => 'Returns a stream of fleshed holds',
1323 { desc => 'Authtoken', type => 'string'},
1324 { desc => 'Hash of optional param: Org unit ID (defaults to workstation org unit), limit, offset, sort (array of: acplo.position, call_number, request_time)',
1329 desc => 'A stream of fleshed holds',
1335 sub print_hold_pull_list_stream {
1336 my($self, $client, $auth, $params) = @_;
1338 my $e = new_editor(authtoken=>$auth);
1339 return $e->die_event unless $e->checkauth;
1341 delete($$params{org_id}) unless (int($$params{org_id}));
1342 delete($$params{limit}) unless (int($$params{limit}));
1343 delete($$params{offset}) unless (int($$params{offset}));
1344 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1345 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1346 $$params{chunk_size} ||= 10;
1348 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1349 return $e->die_event unless $e->allowed('VIEW_HOLD', $$params{org_id });
1352 if ($$params{sort} && @{ $$params{sort} }) {
1353 for my $s (@{ $$params{sort} }) {
1354 if ($s eq 'acplo.position') {
1356 "class" => "acplo", "field" => "position",
1357 "transform" => "coalesce", "params" => [999]
1359 } elsif ($s eq 'call_number') {
1360 push @$sort, {"class" => "acn", "field" => "label"};
1361 } elsif ($s eq 'request_time') {
1362 push @$sort, {"class" => "ahr", "field" => "request_time"};
1366 push @$sort, {"class" => "ahr", "field" => "request_time"};
1369 my $holds_ids = $e->json_query(
1371 "select" => {"ahr" => ["id"]},
1376 "fkey" => "current_copy",
1378 "circ_lib" => $$params{org_id}, "status" => [0,7]
1383 "fkey" => "call_number"
1387 "fkey" => "circ_lib",
1390 "location" => {"=" => {"+acp" => "location"}}
1399 "capture_time" => undef,
1400 "cancel_time" => undef,
1402 {"expire_time" => undef },
1403 {"expire_time" => {">" => "now"}}
1407 (@$sort ? (order_by => $sort) : ()),
1408 ($$params{limit} ? (limit => $$params{limit}) : ()),
1409 ($$params{offset} ? (offset => $$params{offset}) : ())
1410 }, {"subquery" => 1}
1411 ) or return $e->die_event;
1413 $logger->info("about to stream back " . scalar(@$holds_ids) . " holds");
1416 for my $hid (@$holds_ids) {
1417 push @chunk, $e->retrieve_action_hold_request([
1421 "ahr" => ["usr", "current_copy"],
1423 "acp" => ["location", "call_number"],
1429 if (@chunk >= $$params{chunk_size}) {
1430 $client->respond( \@chunk );
1434 $client->respond_complete( \@chunk ) if (@chunk);
1441 __PACKAGE__->register_method(
1442 method => 'fetch_hold_notify',
1443 api_name => 'open-ils.circ.hold_notification.retrieve_by_hold',
1446 Returns a list of hold notification objects based on hold id.
1447 @param authtoken The loggin session key
1448 @param holdid The id of the hold whose notifications we want to retrieve
1449 @return An array of hold notification objects, event on error.
1453 sub fetch_hold_notify {
1454 my( $self, $conn, $authtoken, $holdid ) = @_;
1455 my( $requestor, $evt ) = $U->checkses($authtoken);
1456 return $evt if $evt;
1457 my ($hold, $patron);
1458 ($hold, $evt) = $U->fetch_hold($holdid);
1459 return $evt if $evt;
1460 ($patron, $evt) = $U->fetch_user($hold->usr);
1461 return $evt if $evt;
1463 $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1464 return $evt if $evt;
1466 $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1467 return $U->cstorereq(
1468 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1472 __PACKAGE__->register_method(
1473 method => 'create_hold_notify',
1474 api_name => 'open-ils.circ.hold_notification.create',
1476 Creates a new hold notification object
1477 @param authtoken The login session key
1478 @param notification The hold notification object to create
1479 @return ID of the new object on success, Event on error
1483 sub create_hold_notify {
1484 my( $self, $conn, $auth, $note ) = @_;
1485 my $e = new_editor(authtoken=>$auth, xact=>1);
1486 return $e->die_event unless $e->checkauth;
1488 my $hold = $e->retrieve_action_hold_request($note->hold)
1489 or return $e->die_event;
1490 my $patron = $e->retrieve_actor_user($hold->usr)
1491 or return $e->die_event;
1493 return $e->die_event unless
1494 $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1496 $note->notify_staff($e->requestor->id);
1497 $e->create_action_hold_notification($note) or return $e->die_event;
1502 __PACKAGE__->register_method(
1503 method => 'create_hold_note',
1504 api_name => 'open-ils.circ.hold_note.create',
1506 Creates a new hold request note object
1507 @param authtoken The login session key
1508 @param note The hold note object to create
1509 @return ID of the new object on success, Event on error
1513 sub create_hold_note {
1514 my( $self, $conn, $auth, $note ) = @_;
1515 my $e = new_editor(authtoken=>$auth, xact=>1);
1516 return $e->die_event unless $e->checkauth;
1518 my $hold = $e->retrieve_action_hold_request($note->hold)
1519 or return $e->die_event;
1520 my $patron = $e->retrieve_actor_user($hold->usr)
1521 or return $e->die_event;
1523 return $e->die_event unless
1524 $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn. Probably want something more specific
1526 $e->create_action_hold_request_note($note) or return $e->die_event;
1531 __PACKAGE__->register_method(
1532 method => 'reset_hold',
1533 api_name => 'open-ils.circ.hold.reset',
1535 Un-captures and un-targets a hold, essentially returning
1536 it to the state it was in directly after it was placed,
1537 then attempts to re-target the hold
1538 @param authtoken The login session key
1539 @param holdid The id of the hold
1545 my( $self, $conn, $auth, $holdid ) = @_;
1547 my ($hold, $evt) = $U->fetch_hold($holdid);
1548 return $evt if $evt;
1549 ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1550 return $evt if $evt;
1551 $evt = _reset_hold($self, $reqr, $hold);
1552 return $evt if $evt;
1557 __PACKAGE__->register_method(
1558 method => 'reset_hold_batch',
1559 api_name => 'open-ils.circ.hold.reset.batch'
1562 sub reset_hold_batch {
1563 my($self, $conn, $auth, $hold_ids) = @_;
1565 my $e = new_editor(authtoken => $auth);
1566 return $e->event unless $e->checkauth;
1568 for my $hold_id ($hold_ids) {
1570 my $hold = $e->retrieve_action_hold_request(
1571 [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}])
1572 or return $e->event;
1574 next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1575 _reset_hold($self, $e->requestor, $hold);
1583 my ($self, $reqr, $hold) = @_;
1585 my $e = new_editor(xact =>1, requestor => $reqr);
1587 $logger->info("reseting hold ".$hold->id);
1589 my $hid = $hold->id;
1591 if( $hold->capture_time and $hold->current_copy ) {
1593 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1594 or return $e->die_event;
1596 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1597 $logger->info("setting copy to status 'reshelving' on hold retarget");
1598 $copy->status(OILS_COPY_STATUS_RESHELVING);
1599 $copy->editor($e->requestor->id);
1600 $copy->edit_date('now');
1601 $e->update_asset_copy($copy) or return $e->die_event;
1603 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1605 # We don't want the copy to remain "in transit"
1606 $copy->status(OILS_COPY_STATUS_RESHELVING);
1607 $logger->warn("! reseting hold [$hid] that is in transit");
1608 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1611 my $trans = $e->retrieve_action_transit_copy($transid);
1613 $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1614 my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1);
1615 $logger->info("Transit abort completed with result $evt");
1616 unless ("$evt" eq 1) {
1625 $hold->clear_capture_time;
1626 $hold->clear_current_copy;
1627 $hold->clear_shelf_time;
1628 $hold->clear_shelf_expire_time;
1630 $e->update_action_hold_request($hold) or return $e->die_event;
1634 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1640 __PACKAGE__->register_method(
1641 method => 'fetch_open_title_holds',
1642 api_name => 'open-ils.circ.open_holds.retrieve',
1644 Returns a list ids of un-fulfilled holds for a given title id
1645 @param authtoken The login session key
1646 @param id the id of the item whose holds we want to retrieve
1647 @param type The hold type - M, T, I, V, C, F, R
1651 sub fetch_open_title_holds {
1652 my( $self, $conn, $auth, $id, $type, $org ) = @_;
1653 my $e = new_editor( authtoken => $auth );
1654 return $e->event unless $e->checkauth;
1657 $org ||= $e->requestor->ws_ou;
1659 # return $e->search_action_hold_request(
1660 # { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1662 # XXX make me return IDs in the future ^--
1663 my $holds = $e->search_action_hold_request(
1666 cancel_time => undef,
1668 fulfillment_time => undef
1672 flesh_hold_transits($holds);
1677 sub flesh_hold_transits {
1679 for my $hold ( @$holds ) {
1681 $apputils->simplereq(
1683 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1684 { hold => $hold->id },
1685 { order_by => { ahtc => 'id desc' }, limit => 1 }
1691 sub flesh_hold_notices {
1692 my( $holds, $e ) = @_;
1693 $e ||= new_editor();
1695 for my $hold (@$holds) {
1696 my $notices = $e->search_action_hold_notification(
1698 { hold => $hold->id },
1699 { order_by => { anh => 'notify_time desc' } },
1704 $hold->notify_count(scalar(@$notices));
1706 my $n = $e->retrieve_action_hold_notification($$notices[0])
1707 or return $e->event;
1708 $hold->notify_time($n->notify_time);
1714 __PACKAGE__->register_method(
1715 method => 'fetch_captured_holds',
1716 api_name => 'open-ils.circ.captured_holds.on_shelf.retrieve',
1719 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
1720 @param authtoken The login session key
1721 @param org The org id of the location in question
1725 __PACKAGE__->register_method(
1726 method => 'fetch_captured_holds',
1727 api_name => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
1730 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
1731 @param authtoken The login session key
1732 @param org The org id of the location in question
1736 __PACKAGE__->register_method(
1737 method => 'fetch_captured_holds',
1738 api_name => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
1741 Returns list ids of shelf-expired un-fulfilled holds for a given title id
1742 @param authtoken The login session key
1743 @param org The org id of the location in question
1748 sub fetch_captured_holds {
1749 my( $self, $conn, $auth, $org ) = @_;
1751 my $e = new_editor(authtoken => $auth);
1752 return $e->die_event unless $e->checkauth;
1753 return $e->die_event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
1755 $org ||= $e->requestor->ws_ou;
1758 select => { ahr => ['id'] },
1763 fkey => 'current_copy'
1768 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
1770 capture_time => { "!=" => undef },
1771 current_copy => { "!=" => undef },
1772 fulfillment_time => undef,
1774 cancel_time => undef,
1778 if($self->api_name =~ /expired/) {
1779 $query->{'where'}->{'+ahr'}->{'shelf_expire_time'} = {'<' => 'now'};
1780 $query->{'where'}->{'+ahr'}->{'shelf_time'} = {'!=' => undef};
1782 my $hold_ids = $e->json_query( $query );
1784 for my $hold_id (@$hold_ids) {
1785 if($self->api_name =~ /id_list/) {
1786 $conn->respond($hold_id->{id});
1790 $e->retrieve_action_hold_request([
1794 flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
1795 order_by => {anh => 'notify_time desc'}
1805 __PACKAGE__->register_method(
1806 method => "print_expired_holds_stream",
1807 api_name => "open-ils.circ.captured_holds.expired.print.stream",
1811 sub print_expired_holds_stream {
1812 my ($self, $client, $auth, $params) = @_;
1814 # No need to check specific permissions: we're going to call another method
1815 # that will do that.
1816 my $e = new_editor("authtoken" => $auth);
1817 return $e->die_event unless $e->checkauth;
1819 delete($$params{org_id}) unless (int($$params{org_id}));
1820 delete($$params{limit}) unless (int($$params{limit}));
1821 delete($$params{offset}) unless (int($$params{offset}));
1822 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1823 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1824 $$params{chunk_size} ||= 10;
1826 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1828 my @hold_ids = $self->method_lookup(
1829 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
1830 )->run($auth, $params->{"org_id"});
1835 } elsif (defined $U->event_code($hold_ids[0])) {
1837 return $hold_ids[0];
1840 $logger->info("about to stream back up to " . scalar(@hold_ids) . " expired holds");
1843 my @hid_chunk = splice @hold_ids, 0, $params->{"chunk_size"};
1845 my $result_chunk = $e->json_query({
1847 "acp" => ["barcode"],
1849 first_given_name second_given_name family_name alias
1858 "field" => "id", "fkey" => "current_copy",
1861 "field" => "id", "fkey" => "call_number",
1864 "field" => "id", "fkey" => "record"
1868 "acpl" => {"field" => "id", "fkey" => "location"}
1871 "au" => {"field" => "id", "fkey" => "usr"}
1874 "where" => {"+ahr" => {"id" => \@hid_chunk}}
1875 }) or return $e->die_event;
1876 $client->respond($result_chunk);
1883 __PACKAGE__->register_method(
1884 method => "check_title_hold_batch",
1885 api_name => "open-ils.circ.title_hold.is_possible.batch",
1888 desc => '@see open-ils.circ.title_hold.is_possible.batch',
1890 { desc => 'Authentication token', type => 'string'},
1891 { desc => 'Array of Hash of named parameters', type => 'array'},
1894 desc => 'Array of response objects',
1900 sub check_title_hold_batch {
1901 my($self, $client, $authtoken, $param_list) = @_;
1902 foreach (@$param_list) {
1903 my ($res) = $self->method_lookup('open-ils.circ.title_hold.is_possible')->run($authtoken, $_);
1904 $client->respond($res);
1910 __PACKAGE__->register_method(
1911 method => "check_title_hold",
1912 api_name => "open-ils.circ.title_hold.is_possible",
1914 desc => 'Determines if a hold were to be placed by a given user, ' .
1915 'whether or not said hold would have any potential copies to fulfill it.' .
1916 'The named paramaters of the second argument include: ' .
1917 'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
1918 'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' ,
1920 { desc => 'Authentication token', type => 'string'},
1921 { desc => 'Hash of named parameters', type => 'object'},
1924 desc => 'List of new message IDs (empty if none)',
1930 =head3 check_title_hold (token, hash)
1932 The named fields in the hash are:
1934 patronid - ID of the hold recipient (required)
1935 depth - hold range depth (default 0)
1936 pickup_lib - destination for hold, fallback value for selection_ou
1937 selection_ou - ID of org_unit establishing hard and soft hold boundary settings
1938 issuanceid - ID of the issuance to be held, required for Issuance level hold
1939 titleid - ID (BRN) of the title to be held, required for Title level hold
1940 volume_id - required for Volume level hold
1941 copy_id - required for Copy level hold
1942 mrid - required for Meta-record level hold
1943 hold_type - T, C (or R or F), I, V or M for Title, Copy, Issuance, Volume or Meta-record (default "T")
1945 All key/value pairs are passed on to do_possibility_checks.
1949 # FIXME: better params checking. what other params are required, if any?
1950 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
1951 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still
1952 # used in conditionals, where it may be undefined, causing a warning.
1953 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
1955 sub check_title_hold {
1956 my( $self, $client, $authtoken, $params ) = @_;
1957 my $e = new_editor(authtoken=>$authtoken);
1958 return $e->event unless $e->checkauth;
1960 my %params = %$params;
1961 my $depth = $params{depth} || 0;
1962 my $selection_ou = $params{selection_ou} || $params{pickup_lib};
1964 my $patron = $e->retrieve_actor_user($params{patronid})
1965 or return $e->event;
1967 if( $e->requestor->id ne $patron->id ) {
1968 return $e->event unless
1969 $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
1972 return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
1974 my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
1975 or return $e->event;
1977 my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
1978 my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
1981 my $return_depth = $hard_boundary; # default depth to return on success
1982 if(defined $soft_boundary and $depth < $soft_boundary) {
1983 # work up the tree and as soon as we find a potential copy, use that depth
1984 # also, make sure we don't go past the hard boundary if it exists
1986 # our min boundary is the greater of user-specified boundary or hard boundary
1987 my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?
1988 $hard_boundary : $depth;
1990 my $depth = $soft_boundary;
1991 while($depth >= $min_depth) {
1992 $logger->info("performing hold possibility check with soft boundary $depth");
1993 @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
1995 $return_depth = $depth;
2000 } elsif(defined $hard_boundary and $depth < $hard_boundary) {
2001 # there is no soft boundary, enforce the hard boundary if it exists
2002 $logger->info("performing hold possibility check with hard boundary $hard_boundary");
2003 @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
2005 # no boundaries defined, fall back to user specifed boundary or no boundary
2006 $logger->info("performing hold possibility check with no boundary");
2007 @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
2013 "depth" => $return_depth,
2014 "local_avail" => $status[1]
2016 } elsif ($status[2]) {
2017 my $n = scalar @{$status[2]};
2018 return {"success" => 0, "last_event" => $status[2]->[$n - 1]};
2020 return {"success" => 0};
2026 sub do_possibility_checks {
2027 my($e, $patron, $request_lib, $depth, %params) = @_;
2029 my $issuanceid = $params{issuanceid} || "";
2030 my $titleid = $params{titleid} || "";
2031 my $volid = $params{volume_id};
2032 my $copyid = $params{copy_id};
2033 my $mrid = $params{mrid} || "";
2034 my $pickup_lib = $params{pickup_lib};
2035 my $hold_type = $params{hold_type} || 'T';
2036 my $selection_ou = $params{selection_ou} || $pickup_lib;
2043 if( $hold_type eq OILS_HOLD_TYPE_FORCE || $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_COPY ) {
2045 return $e->event unless $copy = $e->retrieve_asset_copy($copyid);
2046 return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
2047 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2049 return verify_copy_for_hold(
2050 $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib
2053 } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2055 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
2056 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2058 return _check_volume_hold_is_possible(
2059 $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2062 } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
2064 return _check_title_hold_is_possible(
2065 $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2068 } elsif( $hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2070 return _check_issuance_hold_is_possible(
2071 $issuanceid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2074 } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2076 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
2077 my @recs = map { $_->source } @$maps;
2079 for my $rec (@recs) {
2080 @status = _check_title_hold_is_possible(
2081 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2087 # else { Unrecognized hold_type ! } # FIXME: return error? or 0?
2091 sub create_ranged_org_filter {
2092 my($e, $selection_ou, $depth) = @_;
2094 # find the orgs from which this hold may be fulfilled,
2095 # based on the selection_ou and depth
2097 my $top_org = $e->search_actor_org_unit([
2098 {parent_ou => undef},
2099 {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
2102 return () if $depth == $top_org->ou_type->depth;
2104 my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
2105 %org_filter = (circ_lib => []);
2106 push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
2108 $logger->info("hold org filter at depth $depth and selection_ou ".
2109 "$selection_ou created list of @{$org_filter{circ_lib}}");
2115 sub _check_title_hold_is_possible {
2116 my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2118 my $e = new_editor();
2119 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2121 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2122 my $copies = $e->json_query(
2124 select => { acp => ['id', 'circ_lib'] },
2129 fkey => 'call_number',
2133 filter => { id => $titleid },
2138 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2139 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2143 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2148 $logger->info("title possible found ".scalar(@$copies)." potential copies");
2152 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2153 "payload" => {"fail_part" => "no_ultimate_items"}
2158 # -----------------------------------------------------------------------
2159 # sort the copies into buckets based on their circ_lib proximity to
2160 # the patron's home_ou.
2161 # -----------------------------------------------------------------------
2163 my $home_org = $patron->home_ou;
2164 my $req_org = $request_lib->id;
2166 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2168 $prox_cache{$home_org} =
2169 $e->search_actor_org_unit_proximity({from_org => $home_org})
2170 unless $prox_cache{$home_org};
2171 my $home_prox = $prox_cache{$home_org};
2174 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2175 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2177 my @keys = sort { $a <=> $b } keys %buckets;
2180 if( $home_org ne $req_org ) {
2181 # -----------------------------------------------------------------------
2182 # shove the copies close to the request_lib into the primary buckets
2183 # directly before the farthest away copies. That way, they are not
2184 # given priority, but they are checked before the farthest copies.
2185 # -----------------------------------------------------------------------
2186 $prox_cache{$req_org} =
2187 $e->search_actor_org_unit_proximity({from_org => $req_org})
2188 unless $prox_cache{$req_org};
2189 my $req_prox = $prox_cache{$req_org};
2192 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2193 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2195 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2196 my $new_key = $highest_key - 0.5; # right before the farthest prox
2197 my @keys2 = sort { $a <=> $b } keys %buckets2;
2198 for my $key (@keys2) {
2199 last if $key >= $highest_key;
2200 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2204 @keys = sort { $a <=> $b } keys %buckets;
2209 OUTER: for my $key (@keys) {
2210 my @cps = @{$buckets{$key}};
2212 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2214 for my $copyid (@cps) {
2216 next if $seen{$copyid};
2217 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2218 my $copy = $e->retrieve_asset_copy($copyid);
2219 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2221 unless($title) { # grab the title if we don't already have it
2222 my $vol = $e->retrieve_asset_call_number(
2223 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2224 $title = $vol->record;
2227 @status = verify_copy_for_hold(
2228 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2230 last OUTER if $status[0];
2237 sub _check_issuance_hold_is_possible {
2238 my( $issuanceid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2240 my $e = new_editor();
2241 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2243 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2244 my $copies = $e->json_query(
2246 select => { acp => ['id', 'circ_lib'] },
2252 filter => { issuance => $issuanceid }
2254 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2255 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2259 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2265 $logger->info("issuance possible found ".scalar(@$copies)." potential copies");
2269 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2270 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2275 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2276 "payload" => {"fail_part" => "no_ultimate_items"}
2284 # -----------------------------------------------------------------------
2285 # sort the copies into buckets based on their circ_lib proximity to
2286 # the patron's home_ou.
2287 # -----------------------------------------------------------------------
2289 my $home_org = $patron->home_ou;
2290 my $req_org = $request_lib->id;
2292 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2294 $prox_cache{$home_org} =
2295 $e->search_actor_org_unit_proximity({from_org => $home_org})
2296 unless $prox_cache{$home_org};
2297 my $home_prox = $prox_cache{$home_org};
2300 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2301 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2303 my @keys = sort { $a <=> $b } keys %buckets;
2306 if( $home_org ne $req_org ) {
2307 # -----------------------------------------------------------------------
2308 # shove the copies close to the request_lib into the primary buckets
2309 # directly before the farthest away copies. That way, they are not
2310 # given priority, but they are checked before the farthest copies.
2311 # -----------------------------------------------------------------------
2312 $prox_cache{$req_org} =
2313 $e->search_actor_org_unit_proximity({from_org => $req_org})
2314 unless $prox_cache{$req_org};
2315 my $req_prox = $prox_cache{$req_org};
2318 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2319 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2321 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2322 my $new_key = $highest_key - 0.5; # right before the farthest prox
2323 my @keys2 = sort { $a <=> $b } keys %buckets2;
2324 for my $key (@keys2) {
2325 last if $key >= $highest_key;
2326 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2330 @keys = sort { $a <=> $b } keys %buckets;
2335 OUTER: for my $key (@keys) {
2336 my @cps = @{$buckets{$key}};
2338 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2340 for my $copyid (@cps) {
2342 next if $seen{$copyid};
2343 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2344 my $copy = $e->retrieve_asset_copy($copyid);
2345 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2347 unless($title) { # grab the title if we don't already have it
2348 my $vol = $e->retrieve_asset_call_number(
2349 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2350 $title = $vol->record;
2353 @status = verify_copy_for_hold(
2354 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2356 last OUTER if $status[0];
2361 if (!defined($empty_ok)) {
2362 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2363 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2366 return (1,0) if ($empty_ok);
2372 sub _check_volume_hold_is_possible {
2373 my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2374 my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
2375 my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
2376 $logger->info("checking possibility of volume hold for volume ".$vol->id);
2381 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2382 "payload" => {"fail_part" => "no_ultimate_items"}
2388 for my $copy ( @$copies ) {
2389 @status = verify_copy_for_hold(
2390 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
2398 sub verify_copy_for_hold {
2399 my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib ) = @_;
2400 $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
2401 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2402 { patron => $patron,
2403 requestor => $requestor,
2406 title_descriptor => $title->fixed_fields, # this is fleshed into the title object
2407 pickup_lib => $pickup_lib,
2408 request_lib => $request_lib,
2410 show_event_list => 1
2415 (not scalar @$permitted), # true if permitted is an empty arrayref
2417 ($copy->circ_lib == $pickup_lib) and
2418 ($copy->status == OILS_COPY_STATUS_AVAILABLE)
2426 sub find_nearest_permitted_hold {
2429 my $editor = shift; # CStoreEditor object
2430 my $copy = shift; # copy to target
2431 my $user = shift; # staff
2432 my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
2434 my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
2436 my $bc = $copy->barcode;
2438 # find any existing holds that already target this copy
2439 my $old_holds = $editor->search_action_hold_request(
2440 { current_copy => $copy->id,
2441 cancel_time => undef,
2442 capture_time => undef
2446 # hold->type "R" means we need this copy
2447 for my $h (@$old_holds) { return ($h) if $h->hold_type eq 'R'; }
2450 my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
2452 $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
2453 " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
2455 my $fifo = $U->ou_ancestor_setting_value($user->ws_ou, 'circ.holds_fifo');
2457 # search for what should be the best holds for this copy to fulfill
2458 my $best_holds = $U->storagereq(
2459 "open-ils.storage.action.hold_request.nearest_hold.atomic",
2460 $user->ws_ou, $copy->id, 10, $hold_stall_interval, $fifo );
2462 unless(@$best_holds) {
2464 if( my $hold = $$old_holds[0] ) {
2465 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2469 $logger->info("circulator: no suitable holds found for copy $bc");
2470 return (undef, $evt);
2476 # for each potential hold, we have to run the permit script
2477 # to make sure the hold is actually permitted.
2478 for my $holdid (@$best_holds) {
2479 next unless $holdid;
2480 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
2482 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
2483 my $reqr = $editor->retrieve_actor_user($hold->requestor) or next;
2484 my $rlib = $editor->retrieve_actor_org_unit($hold->request_lib) or next;
2486 # see if this hold is permitted
2487 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2488 { patron_id => $hold->usr,
2491 pickup_lib => $hold->pickup_lib,
2492 request_lib => $rlib,
2504 unless( $best_hold ) { # no "good" permitted holds were found
2505 if( my $hold = $$old_holds[0] ) { # can we return a pre-targeted hold?
2506 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2511 $logger->info("circulator: no suitable holds found for copy $bc");
2512 return (undef, $evt);
2515 $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
2517 # indicate a permitted hold was found
2518 return $best_hold if $check_only;
2520 # we've found a permitted hold. we need to "grab" the copy
2521 # to prevent re-targeted holds (next part) from re-grabbing the copy
2522 $best_hold->current_copy($copy->id);
2523 $editor->update_action_hold_request($best_hold)
2524 or return (undef, $editor->event);
2529 # re-target any other holds that already target this copy
2530 for my $old_hold (@$old_holds) {
2531 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
2532 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
2533 $old_hold->id." after a better hold [".$best_hold->id."] was found");
2534 $old_hold->clear_current_copy;
2535 $old_hold->clear_prev_check_time;
2536 $editor->update_action_hold_request($old_hold)
2537 or return (undef, $editor->event);
2538 push(@retarget, $old_hold->id);
2541 return ($best_hold, undef, (@retarget) ? \@retarget : undef);
2549 __PACKAGE__->register_method(
2550 method => 'all_rec_holds',
2551 api_name => 'open-ils.circ.holds.retrieve_all_from_title',
2555 my( $self, $conn, $auth, $title_id, $args ) = @_;
2557 my $e = new_editor(authtoken=>$auth);
2558 $e->checkauth or return $e->event;
2559 $e->allowed('VIEW_HOLD') or return $e->event;
2562 $args->{fulfillment_time} = undef; # we don't want to see old fulfilled holds
2563 $args->{cancel_time} = undef;
2565 my $resp = { volume_holds => [], copy_holds => [], metarecord_holds => [] };
2567 my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
2569 $resp->{metarecord_holds} = $e->search_action_hold_request(
2570 { hold_type => OILS_HOLD_TYPE_METARECORD,
2571 target => $mr_map->metarecord,
2577 $resp->{title_holds} = $e->search_action_hold_request(
2579 hold_type => OILS_HOLD_TYPE_TITLE,
2580 target => $title_id,
2584 my $vols = $e->search_asset_call_number(
2585 { record => $title_id, deleted => 'f' }, {idlist=>1});
2587 return $resp unless @$vols;
2589 $resp->{volume_holds} = $e->search_action_hold_request(
2591 hold_type => OILS_HOLD_TYPE_VOLUME,
2596 my $copies = $e->search_asset_copy(
2597 { call_number => $vols, deleted => 'f' }, {idlist=>1});
2599 return $resp unless @$copies;
2601 $resp->{copy_holds} = $e->search_action_hold_request(
2603 hold_type => OILS_HOLD_TYPE_COPY,
2615 __PACKAGE__->register_method(
2616 method => 'uber_hold',
2618 api_name => 'open-ils.circ.hold.details.retrieve'
2622 my($self, $client, $auth, $hold_id) = @_;
2623 my $e = new_editor(authtoken=>$auth);
2624 $e->checkauth or return $e->event;
2625 return uber_hold_impl($e, $hold_id);
2628 __PACKAGE__->register_method(
2629 method => 'batch_uber_hold',
2632 api_name => 'open-ils.circ.hold.details.batch.retrieve'
2635 sub batch_uber_hold {
2636 my($self, $client, $auth, $hold_ids) = @_;
2637 my $e = new_editor(authtoken=>$auth);
2638 $e->checkauth or return $e->event;
2639 $client->respond(uber_hold_impl($e, $_)) for @$hold_ids;
2643 sub uber_hold_impl {
2644 my($e, $hold_id) = @_;
2648 my $hold = $e->retrieve_action_hold_request(
2653 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
2656 ) or return $e->event;
2658 if($hold->usr->id ne $e->requestor->id) {
2659 # A user is allowed to see his/her own holds
2660 $e->allowed('VIEW_HOLD') or return $e->event;
2661 $hold->notes( # filter out any non-staff ("private") notes
2662 [ grep { !$U->is_true($_->staff) } @{$hold->notes} ] );
2665 # caller is asking for own hold, but may not have permission to view staff notes
2666 unless($e->allowed('VIEW_HOLD')) {
2667 $hold->notes( # filter out any staff notes
2668 [ grep { $U->is_true($_->staff) } @{$hold->notes} ] );
2672 my $user = $hold->usr;
2673 $hold->usr($user->id);
2675 my $card = $e->retrieve_actor_card($user->card)
2676 or return $e->event;
2678 my( $mvr, $volume, $copy ) = find_hold_mvr($e, $hold);
2680 flesh_hold_notices([$hold], $e);
2681 flesh_hold_transits([$hold]);
2683 my $details = retrieve_hold_queue_status_impl($e, $hold);
2690 patron_first => $user->first_given_name,
2691 patron_last => $user->family_name,
2692 patron_barcode => $card->barcode,
2693 patron_alias => $user->alias,
2700 # -----------------------------------------------------
2701 # Returns the MVR object that represents what the
2703 # -----------------------------------------------------
2705 my( $e, $hold ) = @_;
2712 if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2713 my $mr = $e->retrieve_metabib_metarecord($hold->target)
2714 or return $e->event;
2715 $tid = $mr->master_record;
2717 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
2718 $tid = $hold->target;
2720 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2721 $volume = $e->retrieve_asset_call_number($hold->target)
2722 or return $e->event;
2723 $tid = $volume->record;
2725 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2726 $issuance = $e->retrieve_serial_issuance([
2728 {flesh => 1, flesh_fields => {siss => [ qw/subscription/ ]}}
2729 ]) or return $e->event;
2731 $tid = $issuance->subscription->record_entry;
2733 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_COPY ) {
2734 $copy = $e->retrieve_asset_copy([
2736 {flesh => 1, flesh_fields => {acp => ['call_number']}}
2737 ]) or return $e->event;
2739 $volume = $copy->call_number;
2740 $tid = $volume->record;
2743 if(!$copy and ref $hold->current_copy ) {
2744 $copy = $hold->current_copy;
2745 $hold->current_copy($copy->id);
2748 if(!$volume and $copy) {
2749 $volume = $e->retrieve_asset_call_number($copy->call_number);
2752 # TODO return metarcord mvr for M holds
2753 my $title = $e->retrieve_biblio_record_entry($tid);
2754 return ( $U->record_to_mvr($title), $volume, $copy, $issuance );
2758 __PACKAGE__->register_method(
2759 method => 'clear_shelf_process',
2761 api_name => 'open-ils.circ.hold.clear_shelf.process',
2764 1. Find all holds that have expired on the holds shelf
2766 3. If a clear-shelf status is configured, put targeted copies into this status
2767 4. Divide copies into 3 groups: items to transit, items to reshelve, and items
2768 that are needed for holds. No subsequent action is taken on the holds
2769 or items after grouping.
2774 sub clear_shelf_process {
2775 my($self, $client, $auth, $org_id) = @_;
2777 my $e = new_editor(authtoken=>$auth, xact => 1);
2778 $e->checkauth or return $e->die_event;
2780 $org_id ||= $e->requestor->ws_ou;
2781 $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
2783 my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
2785 # Find holds on the shelf that have been there too long
2786 my $hold_ids = $e->search_action_hold_request(
2787 { shelf_expire_time => {'<' => 'now'},
2788 pickup_lib => $org_id,
2789 cancel_time => undef,
2790 fulfillment_time => undef,
2791 shelf_time => {'!=' => undef}
2798 for my $hold_id (@$hold_ids) {
2800 $logger->info("Clear shelf processing hold $hold_id");
2802 my $hold = $e->retrieve_action_hold_request([
2805 flesh_fields => {ahr => ['current_copy']}
2809 $hold->cancel_time('now');
2810 $hold->cancel_cause(2); # Hold Shelf expiration
2811 $e->update_action_hold_request($hold) or return $e->die_event;
2813 my $copy = $hold->current_copy;
2815 if($copy_status or $copy_status == 0) {
2816 # if a clear-shelf copy status is defined, update the copy
2817 $copy->status($copy_status);
2818 $copy->edit_date('now');
2819 $copy->editor($e->requestor->id);
2820 $e->update_asset_copy($copy) or return $e->die_event;
2823 push(@holds, $hold);
2828 for my $hold (@holds) {
2830 my $copy = $hold->current_copy;
2832 my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
2836 # copy is needed for a hold
2837 $client->respond({action => 'hold', copy => $copy, hold_id => $hold->id});
2839 } elsif($copy->circ_lib != $e->requestor->ws_ou) {
2841 # copy needs to transit
2842 $client->respond({action => 'transit', copy => $copy, hold_id => $hold->id});
2846 # copy needs to go back to the shelf
2847 $client->respond({action => 'shelf', copy => $copy, hold_id => $hold->id});
2851 # tell the client we're done
2852 $client->respond_complete;
2854 # fire off the hold cancelation trigger
2855 my $trigger = OpenSRF::AppSession->connect('open-ils.trigger');
2857 for my $hold (@holds) {
2859 my $req = $trigger->request(
2860 'open-ils.trigger.event.autocreate',
2861 'hold_request.cancel.expire_holds_shelf',
2864 # wait for response so don't flood the service
2868 $trigger->disconnect;
2871 # tell the client we're done
2872 $client->respond_complete;
2876 __PACKAGE__->register_method(
2877 method => 'usr_hold_summary',
2878 api_name => 'open-ils.circ.holds.user_summary',
2880 Returns a summary of holds statuses for a given user
2884 sub usr_hold_summary {
2885 my($self, $conn, $auth, $user_id) = @_;
2887 my $e = new_editor(authtoken=>$auth);
2888 $e->checkauth or return $e->event;
2889 $e->allowed('VIEW_HOLD') or return $e->event;
2891 my $holds = $e->search_action_hold_request(
2894 fulfillment_time => undef,
2895 cancel_time => undef,
2899 my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
2900 $summary{_hold_status($e, $_)} += 1 for @$holds;
2906 __PACKAGE__->register_method(
2907 method => 'hold_has_copy_at',
2908 api_name => 'open-ils.circ.hold.has_copy_at',
2911 'Returns the ID of the found copy and name of the shelving location if there is ' .
2912 'an available copy at the specified org unit. Returns empty hash otherwise. ' .
2913 'The anticipated use for this method is to determine whether an item is ' .
2914 'available at the library where the user is placing the hold (or, alternatively, '.
2915 'at the pickup library) to encourage bypassing the hold placement and just ' .
2916 'checking out the item.' ,
2918 { desc => 'Authentication Token', type => 'string' },
2919 { desc => 'Method Arguments. Options include: hold_type, hold_target, org_unit. '
2920 . 'hold_type is the hold type code (T, V, C, M, ...). '
2921 . 'hold_target is the identifier of the hold target object. '
2922 . 'org_unit is org unit ID.',
2927 desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
2933 sub hold_has_copy_at {
2934 my($self, $conn, $auth, $args) = @_;
2936 my $e = new_editor(authtoken=>$auth);
2937 $e->checkauth or return $e->event;
2939 my $hold_type = $$args{hold_type};
2940 my $hold_target = $$args{hold_target};
2941 my $org_unit = $$args{org_unit};
2944 select => {acp => ['id'], acpl => ['name']},
2947 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
2948 ccs => {field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2951 where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit}},
2955 if($hold_type eq 'C') {
2957 $query->{where}->{'+acp'}->{id} = $hold_target;
2959 } elsif($hold_type eq 'V') {
2961 $query->{where}->{'+acp'}->{call_number} = $hold_target;
2963 } elsif($hold_type eq 'T') {
2965 $query->{from}->{acp}->{acn} = {
2967 fkey => 'call_number',
2971 filter => {id => $hold_target},
2979 $query->{from}->{acp}->{acn} = {
2981 fkey => 'call_number',
2990 filter => {metarecord => $hold_target},
2998 my $res = $e->json_query($query)->[0] or return {};
2999 return {copy => $res->{id}, location => $res->{name}} if $res;
3003 # returns true if the user already has an item checked out
3004 # that could be used to fulfill the requested hold.
3005 sub hold_item_is_checked_out {
3006 my($e, $user_id, $hold_type, $hold_target) = @_;
3009 select => {acp => ['id']},
3010 from => {acp => {}},
3014 in => { # copies for circs the user has checked out
3015 select => {circ => ['target_copy']},
3019 checkin_time => undef,
3021 {stop_fines => ["MAXFINES","LONGOVERDUE"]},
3022 {stop_fines => undef}
3032 if($hold_type eq 'C' || $hold_type eq 'R' || $hold_type eq 'F') {
3034 $query->{where}->{'+acp'}->{id}->{in}->{where}->{'target_copy'} = $hold_target;
3036 } elsif($hold_type eq 'V') {
3038 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3040 } elsif($hold_type eq 'I') {
3042 $query->{from}->{acp}->{sitem} = {
3045 filter => {issuance => $hold_target},
3048 } elsif($hold_type eq 'T') {
3050 $query->{from}->{acp}->{acn} = {
3052 fkey => 'call_number',
3056 filter => {id => $hold_target},
3064 $query->{from}->{acp}->{acn} = {
3066 fkey => 'call_number',
3075 filter => {metarecord => $hold_target},
3083 return $e->json_query($query)->[0];
3086 __PACKAGE__->register_method(
3087 method => 'change_hold_title',
3088 api_name => 'open-ils.circ.hold.change_title',
3091 Updates all title level holds targeting the specified bibs to point a new bib./,
3093 { desc => 'Authentication Token', type => 'string' },
3094 { desc => 'New Target Bib Id', type => 'number' },
3095 { desc => 'Old Target Bib Ids', type => 'array' },
3097 return => { desc => '1 on success' }
3101 sub change_hold_title {
3102 my( $self, $client, $auth, $new_bib_id, $bib_ids ) = @_;
3104 my $e = new_editor(authtoken=>$auth, xact=>1);
3105 return $e->die_event unless $e->checkauth;
3107 my $holds = $e->search_action_hold_request(
3110 cancel_time => undef,
3111 fulfillment_time => undef,
3117 flesh_fields => { ahr => ['usr'] }
3123 for my $hold (@$holds) {
3124 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3125 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3126 $hold->target( $new_bib_id );
3127 $e->update_action_hold_request($hold) or return $e->die_event;
3136 __PACKAGE__->register_method(
3137 method => 'rec_hold_count',
3138 api_name => 'open-ils.circ.bre.holds.count',
3140 desc => q/Returns the total number of holds that target the
3141 selected bib record or its associated copies and call_numbers/,
3143 { desc => 'Bib ID', type => 'number' },
3145 return => {desc => 'Hold count', type => 'number'}
3149 __PACKAGE__->register_method(
3150 method => 'rec_hold_count',
3151 api_name => 'open-ils.circ.mmr.holds.count',
3153 desc => q/Returns the total number of holds that target the
3154 selected metarecord or its associated copies, call_numbers, and bib records/,
3156 { desc => 'Metarecord ID', type => 'number' },
3158 return => {desc => 'Hold count', type => 'number'}
3162 sub rec_hold_count {
3163 my($self, $conn, $target_id) = @_;
3170 filter => {metarecord => $target_id}
3177 filter => { id => $target_id },
3182 if($self->api_name =~ /mmr/) {
3183 delete $bre_join->{bre}->{filter};
3184 $bre_join->{bre}->{join} = $mmr_join;
3190 fkey => 'call_number',
3196 select => {ahr => [{column => 'id', transform => 'count', alias => 'count'}]},
3200 cancel_time => undef,
3201 fulfillment_time => undef,
3208 select => {acp => ['id']},
3209 from => { acp => $cn_join }
3219 select => {acn => ['id']},
3220 from => {acn => $bre_join}
3228 target => $target_id
3236 if($self->api_name =~ /mmr/) {
3237 $query->{where}->{'+ahr'}->{'-or'}->[2] = {
3242 select => {bre => ['id']},
3243 from => {bre => $mmr_join}
3249 $query->{where}->{'+ahr'}->{'-or'}->[3] = {
3252 target => $target_id
3258 return new_editor()->json_query($query)->[0]->{count};