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",
43 api_name => "open-ils.circ.holds.create",
45 desc => "Create a new hold for an item. From a permissions perspective, " .
46 "the login session is used as the 'requestor' of the hold. " .
47 "The hold recipient is determined by the 'usr' setting within the hold object. " .
48 'First we verify the requestor has holds request permissions. ' .
49 'Then we verify that the recipient is allowed to make the given hold. ' .
50 'If not, we see if the requestor has "override" capabilities. If not, ' .
51 'a permission exception is returned. If permissions allow, we cycle ' .
52 'through the set of holds objects and create. ' .
53 'If the recipient does not have permission to place multiple holds ' .
54 'on a single title and said operation is attempted, a permission ' .
55 'exception is returned',
57 { desc => 'Authentication token', type => 'string' },
58 { desc => 'Hold object for hold to be created', type => 'object' }
61 desc => 'Undef on success, -1 on missing arg, event (or ref to array of events) on error(s)',
66 __PACKAGE__->register_method(
67 method => "create_hold",
68 api_name => "open-ils.circ.holds.create.override",
69 notes => '@see open-ils.circ.holds.create',
71 desc => "If the recipient is not allowed to receive the requested hold, " .
72 "call this method to attempt the override",
74 { desc => 'Authentication token', type => 'string' },
75 { desc => 'Hold object for hold to be created', type => 'object' }
78 desc => 'Undef on success, -1 on missing arg, event (or ref to array of events) on error(s)',
84 my( $self, $conn, $auth, $hold ) = @_;
85 my $e = new_editor(authtoken=>$auth, xact=>1);
86 return $e->event unless $e->checkauth;
88 return -1 unless $hold;
89 my $override = 1 if $self->api_name =~ /override/;
93 my $requestor = $e->requestor;
94 my $recipient = $requestor;
96 if( $requestor->id ne $hold->usr ) {
97 # Make sure the requestor is allowed to place holds for
98 # the recipient if they are not the same people
99 $recipient = $e->retrieve_actor_user($hold->usr) or return $e->event;
100 $e->allowed('REQUEST_HOLDS', $recipient->home_ou) or return $e->event;
103 # Now make sure the recipient is allowed to receive the specified hold
104 my $porg = $recipient->home_ou;
105 my $rid = $e->requestor->id;
106 my $t = $hold->hold_type;
108 # See if a duplicate hold already exists
110 usr => $recipient->id,
112 fulfillment_time => undef,
113 target => $hold->target,
114 cancel_time => undef,
117 $sargs->{holdable_formats} = $hold->holdable_formats if $t eq 'M';
119 my $existing = $e->search_action_hold_request($sargs);
120 push( @events, OpenILS::Event->new('HOLD_EXISTS')) if @$existing;
122 my $checked_out = hold_item_is_checked_out($e, $recipient->id, $hold->hold_type, $hold->target);
123 push( @events, OpenILS::Event->new('HOLD_ITEM_CHECKED_OUT')) if $checked_out;
125 if ( $t eq OILS_HOLD_TYPE_METARECORD ) {
126 return $e->event unless $e->allowed('MR_HOLDS', $porg);
127 } elsif ( $t eq OILS_HOLD_TYPE_TITLE ) {
128 return $e->event unless $e->allowed('TITLE_HOLDS', $porg);
129 } elsif ( $t eq OILS_HOLD_TYPE_VOLUME ) {
130 return $e->event unless $e->allowed('VOLUME_HOLDS', $porg);
131 } elsif ( $t eq OILS_HOLD_TYPE_COPY ) {
132 return $e->event unless $e->allowed('COPY_HOLDS', $porg);
136 $override or return \@events;
137 for my $evt (@events) {
139 my $name = $evt->{textcode};
140 return $e->event unless $e->allowed("$name.override", $porg);
144 # set the configured expire time
145 unless($hold->expire_time) {
146 my $interval = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_HOLD_EXPIRE);
148 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
149 $hold->expire_time($U->epoch2ISO8601($date->epoch));
153 $hold->requestor($e->requestor->id);
154 $hold->request_lib($e->requestor->ws_ou);
155 $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
156 $hold = $e->create_action_hold_request($hold) or return $e->event;
160 $conn->respond_complete($hold->id);
163 'open-ils.storage.action.hold_request.copy_targeter',
164 undef, $hold->id ) unless $U->is_true($hold->frozen);
170 my( $self, $client, $login_session, @holds) = @_;
172 if(!@holds){return 0;}
173 my( $user, $evt ) = $apputils->checkses($login_session);
176 my $holdsref = (ref($holds[0]) eq 'ARRAY') ? $holds[0] : [ @holds ];
178 $logger->debug("Iterating over " . scalar(@$holdsref) . " holds requests...");
180 for my $hold (@$holdsref) {
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);
195 # am I allowed to place holds for this user?
196 if($hold->requestor ne $hold->usr) {
197 my $perm = _check_request_holds_perm($user->id, $user->home_ou);
198 return $perm if $perm;
201 # is this user allowed to have holds of this type?
202 my $perm = _check_holds_perm($type, $hold->requestor, $recipient->home_ou);
203 return $perm if $perm;
205 #enforce the fact that the login is the one requesting the hold
206 $hold->requestor($user->id);
207 $hold->selection_ou($recipient->home_ou) unless $hold->selection_ou;
209 my $resp = $apputils->simplereq(
211 'open-ils.storage.direct.action.hold_request.create', $hold );
214 return OpenSRF::EX::ERROR ("Error creating hold");
221 # makes sure that a user has permission to place the type of requested hold
222 # returns the Perm exception if not allowed, returns undef if all is well
223 sub _check_holds_perm {
224 my($type, $user_id, $org_id) = @_;
228 $evt = $apputils->check_perms($user_id, $org_id, "MR_HOLDS" );
229 } elsif ($type eq "T") {
230 $evt = $apputils->check_perms($user_id, $org_id, "TITLE_HOLDS" );
231 } elsif($type eq "V") {
232 $evt = $apputils->check_perms($user_id, $org_id, "VOLUME_HOLDS");
233 } elsif($type eq "C") {
234 $evt = $apputils->check_perms($user_id, $org_id, "COPY_HOLDS" );
241 # tests if the given user is allowed to place holds on another's behalf
242 sub _check_request_holds_perm {
245 if (my $evt = $apputils->check_perms(
246 $user_id, $org_id, "REQUEST_HOLDS")) {
251 my $ses_is_req_note = 'The login session is the requestor. If the requestor is different from the user, ' .
252 'then the requestor must have VIEW_HOLD permissions';
254 __PACKAGE__->register_method(
255 method => "retrieve_holds_by_id",
256 api_name => "open-ils.circ.holds.retrieve_by_id",
258 desc => "Retrieve the hold, with hold transits attached, for the specified ID. $ses_is_req_note",
260 { desc => 'Authentication token', type => 'string' },
261 { desc => 'Hold ID', type => 'number' }
264 desc => 'Hold object with transits attached, event on error',
270 sub retrieve_holds_by_id {
271 my($self, $client, $auth, $hold_id) = @_;
272 my $e = new_editor(authtoken=>$auth);
273 $e->checkauth or return $e->event;
274 $e->allowed('VIEW_HOLD') or return $e->event;
276 my $holds = $e->search_action_hold_request(
278 { id => $hold_id , fulfillment_time => undef },
280 order_by => { ahr => "request_time" },
282 flesh_fields => {ahr => ['notes']}
287 flesh_hold_transits($holds);
288 flesh_hold_notices($holds, $e);
293 __PACKAGE__->register_method(
294 method => "retrieve_holds",
295 api_name => "open-ils.circ.holds.retrieve",
297 desc => "Retrieves all the holds, with hold transits attached, for the specified user. $ses_is_req_note",
299 { desc => 'Authentication token', type => 'string' },
300 { desc => 'User ID', type => 'integer' }
303 desc => 'list of holds, event on error',
308 __PACKAGE__->register_method(
309 method => "retrieve_holds",
310 api_name => "open-ils.circ.holds.id_list.retrieve",
313 desc => "Retrieves all the hold IDs, for the specified user. $ses_is_req_note",
315 { desc => 'Authentication token', type => 'string' },
316 { desc => 'User ID', type => 'integer' }
319 desc => 'list of holds, event on error',
324 __PACKAGE__->register_method(
325 method => "retrieve_holds",
326 api_name => "open-ils.circ.holds.canceled.retrieve",
329 desc => "Retrieves all the cancelled holds for the specified user. $ses_is_req_note",
331 { desc => 'Authentication token', type => 'string' },
332 { desc => 'User ID', type => 'integer' }
335 desc => 'list of holds, event on error',
340 __PACKAGE__->register_method(
341 method => "retrieve_holds",
342 api_name => "open-ils.circ.holds.canceled.id_list.retrieve",
345 desc => "Retrieves list of cancelled hold IDs for the specified user. $ses_is_req_note",
347 { desc => 'Authentication token', type => 'string' },
348 { desc => 'User ID', type => 'integer' }
351 desc => 'list of hold IDs, event on error',
358 my ($self, $client, $auth, $user_id) = @_;
360 my $e = new_editor(authtoken=>$auth);
361 return $e->event unless $e->checkauth;
362 $user_id = $e->requestor->id unless defined $user_id;
364 my $notes_filter = {staff => 'f'};
365 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
366 unless($user_id == $e->requestor->id) {
367 if($e->allowed('VIEW_HOLD', $user->home_ou)) {
368 $notes_filter = {staff => 't'}
370 my $allowed = OpenILS::Application::Actor::Friends->friend_perm_allowed(
371 $e, $user_id, $e->requestor->id, 'hold.view');
372 return $e->event unless $allowed;
375 # staff member looking at his/her own holds can see staff and non-staff notes
376 $notes_filter = {} if $e->allowed('VIEW_HOLD', $user->home_ou);
381 if($self->api_name !~ /canceled/) {
383 # Fetch the active holds
385 $holds = $e->search_action_hold_request([
387 fulfillment_time => undef,
388 cancel_time => undef,
390 {order_by => {ahr => "request_time"}}
395 # Fetch the canceled holds
398 my $cancel_count = $U->ou_ancestor_setting_value(
399 $e->requestor->ws_ou, 'circ.holds.canceled.display_count', $e);
401 unless($cancel_count) {
402 $cancel_age = $U->ou_ancestor_setting_value(
403 $e->requestor->ws_ou, 'circ.holds.canceled.display_age', $e);
406 if($cancel_count) { # limit by count
408 # find at most cancel_count canceled holds
409 $holds = $e->search_action_hold_request([
411 fulfillment_time => undef,
412 cancel_time => {'!=' => undef},
414 {order_by => {ahr => "cancel_time desc"}, limit => $cancel_count}
417 } elsif($cancel_age) { # limit by age
419 # find all of the canceled holds that were canceled within the configured time frame
420 my $date = DateTime->now->subtract(seconds => OpenSRF::Utils::interval_to_seconds($cancel_age));
421 $date = $U->epoch2ISO8601($date->epoch);
423 $holds = $e->search_action_hold_request([
425 fulfillment_time => undef,
426 cancel_time => {'>=' => $date},
428 {order_by => {ahr => "cancel_time desc"}}
433 if( $self->api_name !~ /id_list/ ) {
434 for my $hold ( @$holds ) {
435 $hold->notes($e->search_action_hold_request_note({hold => $hold->id, %$notes_filter}));
437 $e->search_action_hold_transit_copy([
439 {order_by => {ahtc => 'id desc'}, limit => 1}])->[0]
445 return [ map { $_->id } @$holds ];
449 __PACKAGE__->register_method(
450 method => 'user_hold_count',
451 api_name => 'open-ils.circ.hold.user.count'
454 sub user_hold_count {
455 my ( $self, $conn, $auth, $userid ) = @_;
456 my $e = new_editor( authtoken => $auth );
457 return $e->event unless $e->checkauth;
458 my $patron = $e->retrieve_actor_user($userid)
460 return $e->event unless $e->allowed( 'VIEW_HOLD', $patron->home_ou );
461 return __user_hold_count( $self, $e, $userid );
464 sub __user_hold_count {
465 my ( $self, $e, $userid ) = @_;
466 my $holds = $e->search_action_hold_request(
469 fulfillment_time => undef,
470 cancel_time => undef,
475 return scalar(@$holds);
479 __PACKAGE__->register_method(
480 method => "retrieve_holds_by_pickup_lib",
481 api_name => "open-ils.circ.holds.retrieve_by_pickup_lib",
483 "Retrieves all the holds, with hold transits attached, for the specified pickup_ou id."
486 __PACKAGE__->register_method(
487 method => "retrieve_holds_by_pickup_lib",
488 api_name => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
489 notes => "Retrieves all the hold ids for the specified pickup_ou id. "
492 sub retrieve_holds_by_pickup_lib {
493 my ($self, $client, $login_session, $ou_id) = @_;
495 #FIXME -- put an appropriate permission check here
496 #my( $user, $target, $evt ) = $apputils->checkses_requestor(
497 # $login_session, $user_id, 'VIEW_HOLD' );
498 #return $evt if $evt;
500 my $holds = $apputils->simplereq(
502 "open-ils.cstore.direct.action.hold_request.search.atomic",
504 pickup_lib => $ou_id ,
505 fulfillment_time => undef,
508 { order_by => { ahr => "request_time" } }
511 if ( ! $self->api_name =~ /id_list/ ) {
512 flesh_hold_transits($holds);
516 return [ map { $_->id } @$holds ];
520 __PACKAGE__->register_method(
521 method => "uncancel_hold",
522 api_name => "open-ils.circ.hold.uncancel"
526 my($self, $client, $auth, $hold_id) = @_;
527 my $e = new_editor(authtoken=>$auth, xact=>1);
528 return $e->event unless $e->checkauth;
530 my $hold = $e->retrieve_action_hold_request($hold_id)
531 or return $e->die_event;
532 return $e->die_event unless $e->allowed('CANCEL_HOLDS', $hold->request_lib);
534 return 0 if $hold->fulfillment_time;
535 return 1 unless $hold->cancel_time;
537 # if configured to reset the request time, also reset the expire time
538 if($U->ou_ancestor_setting_value(
539 $hold->request_lib, 'circ.holds.uncancel.reset_request_time', $e)) {
541 $hold->request_time('now');
542 my $interval = $U->ou_ancestor_setting_value($hold->request_lib, OILS_SETTING_HOLD_EXPIRE);
544 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
545 $hold->expire_time($U->epoch2ISO8601($date->epoch));
549 $hold->clear_cancel_time;
550 $hold->clear_cancel_cause;
551 $hold->clear_cancel_note;
552 $e->update_action_hold_request($hold) or return $e->die_event;
555 $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
561 __PACKAGE__->register_method(
562 method => "cancel_hold",
563 api_name => "open-ils.circ.hold.cancel",
565 desc => 'Cancels the specified hold. The login session is the requestor. If the requestor is different from the usr field ' .
566 'on the hold, the requestor must have CANCEL_HOLDS permissions. The hold may be either the hold object or the hold id',
568 {desc => 'Authentication token', type => 'string'},
569 {desc => 'Hold ID', type => 'number'},
570 {desc => 'Cause of Cancellation', type => 'string'},
571 {desc => 'Note', type => 'string'}
574 desc => '1 on success, event on error'
580 my($self, $client, $auth, $holdid, $cause, $note) = @_;
582 my $e = new_editor(authtoken=>$auth, xact=>1);
583 return $e->event unless $e->checkauth;
585 my $hold = $e->retrieve_action_hold_request($holdid)
588 if( $e->requestor->id ne $hold->usr ) {
589 return $e->event unless $e->allowed('CANCEL_HOLDS');
592 return 1 if $hold->cancel_time;
594 # If the hold is captured, reset the copy status
595 if( $hold->capture_time and $hold->current_copy ) {
597 my $copy = $e->retrieve_asset_copy($hold->current_copy)
600 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
601 $logger->info("canceling hold $holdid whose item is on the holds shelf");
602 # $logger->info("setting copy to status 'reshelving' on hold cancel");
603 # $copy->status(OILS_COPY_STATUS_RESHELVING);
604 # $copy->editor($e->requestor->id);
605 # $copy->edit_date('now');
606 # $e->update_asset_copy($copy) or return $e->event;
608 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
611 $logger->warn("! canceling hold [$hid] that is in transit");
612 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
615 my $trans = $e->retrieve_action_transit_copy($transid);
616 # Leave the transit alive, but set the copy status to
617 # reshelving so it will be properly reshelved when it gets back home
619 $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
620 $e->update_action_transit_copy($trans) or return $e->die_event;
626 $hold->cancel_time('now');
627 $hold->cancel_cause($cause);
628 $hold->cancel_note($note);
629 $e->update_action_hold_request($hold)
632 delete_hold_copy_maps($self, $e, $hold->id);
638 sub delete_hold_copy_maps {
643 my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
645 $editor->delete_action_hold_copy_map($_)
646 or return $editor->event;
652 my $update_hold_desc = 'The login session is the requestor. ' .
653 'If the requestor is different from the usr field on the hold, ' .
654 'the requestor must have UPDATE_HOLDS permissions. ' .
655 'If supplying a hash of hold data, "id" must be included. ' .
656 'The hash is ignored if a hold object is supplied, ' .
657 'so you should supply only one kind of hold data argument.' ;
659 __PACKAGE__->register_method(
660 method => "update_hold",
661 api_name => "open-ils.circ.hold.update",
663 desc => "Updates the specified hold. $update_hold_desc",
665 {desc => 'Authentication token', type => 'string'},
666 {desc => 'Hold Object', type => 'object'},
667 {desc => 'Hash of values to be applied', type => 'object'}
670 desc => 'Hold ID on success, event on error',
676 __PACKAGE__->register_method(
677 method => "batch_update_hold",
678 api_name => "open-ils.circ.hold.update.batch",
681 desc => "Updates the specified hold(s). $update_hold_desc",
683 {desc => 'Authentication token', type => 'string'},
684 {desc => 'Array of hold obejcts', type => 'array' },
685 {desc => 'Array of hashes of values to be applied', type => 'array' }
688 desc => 'Hold ID per success, event per error',
694 my($self, $client, $auth, $hold, $values) = @_;
695 my $e = new_editor(authtoken=>$auth, xact=>1);
696 return $e->die_event unless $e->checkauth;
697 my $resp = update_hold_impl($self, $e, $hold, $values);
698 return $resp if $U->event_code($resp);
699 $e->commit; # FIXME: update_hold_impl already does $e->commit ??
703 sub batch_update_hold {
704 my($self, $client, $auth, $hold_list, $values_list) = @_;
705 my $e = new_editor(authtoken=>$auth);
706 return $e->die_event unless $e->checkauth;
708 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.
710 $values_list ||= []; # FIXME: either move this above $count declaration, or send an event if both lists undef. Probably the latter.
712 # FIXME: Failing over to [] guarantees warnings for "Use of unitialized value" in update_hold_impl call.
713 # FIXME: We should be sure we only call update_hold_impl with hold object OR hash, not both.
715 for my $idx (0..$count-1) {
717 my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
718 $e->xact_commit unless $U->event_code($resp);
719 $client->respond($resp);
723 return undef; # not in the register return type, assuming we should always have at least one list populated
726 sub update_hold_impl {
727 my($self, $e, $hold, $values) = @_;
730 $hold = $e->retrieve_action_hold_request($values->{id})
731 or return $e->die_event;
732 $hold->$_($values->{$_}) for keys %$values;
735 my $orig_hold = $e->retrieve_action_hold_request($hold->id)
736 or return $e->die_event;
738 # don't allow the user to be changed
739 return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
741 if($hold->usr ne $e->requestor->id) {
742 # if the hold is for a different user, make sure the
743 # requestor has the appropriate permissions
744 my $usr = $e->retrieve_actor_user($hold->usr)
745 or return $e->die_event;
746 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
750 # --------------------------------------------------------------
751 # Changing the request time is like playing God
752 # --------------------------------------------------------------
753 if($hold->request_time ne $orig_hold->request_time) {
754 return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
755 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
758 # --------------------------------------------------------------
759 # if the hold is on the holds shelf or in transit and the pickup
760 # lib changes we need to create a new transit.
761 # --------------------------------------------------------------
762 if($orig_hold->pickup_lib ne $hold->pickup_lib) {
764 my $status = _hold_status($e, $hold);
766 if($status == 3) { # in transit
768 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
769 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
771 $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
773 # update the transit to reflect the new pickup location
774 my $transit = $e->search_action_hold_transit_copy(
775 {hold=>$hold->id, dest_recv_time => undef})->[0]
776 or return $e->die_event;
778 $transit->prev_dest($transit->dest); # mark the previous destination on the transit
779 $transit->dest($hold->pickup_lib);
780 $e->update_action_hold_transit_copy($transit) or return $e->die_event;
782 } elsif($status == 4) { # on holds shelf
784 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
785 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
787 $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
789 # create the new transit
790 my $evt = transit_hold($e, $orig_hold, $hold, $e->retrieve_asset_copy($hold->current_copy));
795 update_hold_if_frozen($self, $e, $hold, $orig_hold);
796 $e->update_action_hold_request($hold) or return $e->die_event;
799 # a change to mint-condition changes the set of potential copies, so retarget the hold;
800 if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
801 _reset_hold($self, $e->requestor, $hold)
808 my($e, $orig_hold, $hold, $copy) = @_;
809 my $src = $orig_hold->pickup_lib;
810 my $dest = $hold->pickup_lib;
812 $logger->info("putting hold into transit on pickup_lib update");
814 my $transit = Fieldmapper::action::hold_transit_copy->new;
815 $transit->hold($hold->id);
816 $transit->source($src);
817 $transit->dest($dest);
818 $transit->target_copy($copy->id);
819 $transit->source_send_time('now');
820 $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
822 $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
823 $copy->editor($e->requestor->id);
824 $copy->edit_date('now');
826 $e->create_action_hold_transit_copy($transit) or return $e->die_event;
827 $e->update_asset_copy($copy) or return $e->die_event;
831 # if the hold is frozen, this method ensures that the hold is not "targeted",
832 # that is, it clears the current_copy and prev_check_time to essentiallly
833 # reset the hold. If it is being activated, it runs the targeter in the background
834 sub update_hold_if_frozen {
835 my($self, $e, $hold, $orig_hold) = @_;
836 return if $hold->capture_time;
838 if($U->is_true($hold->frozen)) {
839 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
840 $hold->clear_current_copy;
841 $hold->clear_prev_check_time;
844 if($U->is_true($orig_hold->frozen)) {
845 $logger->info("Running targeter on activated hold ".$hold->id);
846 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
851 __PACKAGE__->register_method(
852 method => "hold_note_CUD",
853 api_name => "open-ils.circ.hold_request.note.cud",
855 desc => 'Create, update or delete a hold request note. If the operator (from Auth. token) '
856 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
858 { desc => 'Authentication token', type => 'string' },
859 { desc => 'Hold note object', type => 'object' }
862 desc => 'Returns the note ID, event on error'
868 my($self, $conn, $auth, $note) = @_;
870 my $e = new_editor(authtoken => $auth, xact => 1);
871 return $e->die_event unless $e->checkauth;
873 my $hold = $e->retrieve_action_hold_request($note->hold)
874 or return $e->die_event;
876 if($hold->usr ne $e->requestor->id) {
877 my $usr = $e->retrieve_actor_user($hold->usr);
878 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
879 $note->staff('t') if $note->isnew;
883 $e->create_action_hold_request_note($note) or return $e->die_event;
884 } elsif($note->ischanged) {
885 $e->update_action_hold_request_note($note) or return $e->die_event;
886 } elsif($note->isdeleted) {
887 $e->delete_action_hold_request_note($note) or return $e->die_event;
895 __PACKAGE__->register_method(
896 method => "retrieve_hold_status",
897 api_name => "open-ils.circ.hold.status.retrieve",
899 desc => 'Calculates the current status of the hold. The requestor must have ' .
900 'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
902 { desc => 'Hold ID', type => 'number' }
905 # type => 'number', # event sometimes
906 desc => <<'END_OF_DESC'
907 Returns event on error or:
908 -1 on error (for now),
909 1 for 'waiting for copy to become available',
910 2 for 'waiting for copy capture',
913 5 for 'hold-shelf-delay'
919 sub retrieve_hold_status {
920 my($self, $client, $auth, $hold_id) = @_;
922 my $e = new_editor(authtoken => $auth);
923 return $e->event unless $e->checkauth;
924 my $hold = $e->retrieve_action_hold_request($hold_id)
927 if( $e->requestor->id != $hold->usr ) {
928 return $e->event unless $e->allowed('VIEW_HOLD');
931 return _hold_status($e, $hold);
937 return 1 unless $hold->current_copy;
938 return 2 unless $hold->capture_time;
940 my $copy = $hold->current_copy;
941 unless( ref $copy ) {
942 $copy = $e->retrieve_asset_copy($hold->current_copy)
946 return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
948 if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
950 my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
951 return 4 unless $hs_wait_interval;
953 # if a hold_shelf_status_delay interval is defined and start_time plus
954 # the interval is greater than now, consider the hold to be in the virtual
955 # "on its way to the holds shelf" status. Return 5.
957 my $transit = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
958 my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
959 $start_time = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
960 my $end_time = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
962 return 5 if $end_time > DateTime->now;
971 __PACKAGE__->register_method(
972 method => "retrieve_hold_queue_stats",
973 api_name => "open-ils.circ.hold.queue_stats.retrieve",
975 desc => 'Returns summary data about the state of a hold',
977 { desc => 'Authentication token', type => 'string'},
978 { desc => 'Hold ID', type => 'number'},
981 desc => q/Summary object with keys:
982 total_holds : total holds in queue
983 queue_position : current queue position
984 potential_copies : number of potential copies for this hold
985 estimated_wait : estimated wait time in days
987 -1 => error or unexpected state,
988 1 => 'waiting for copy to become available',
989 2 => 'waiting for copy capture',
992 5 => 'hold-shelf-delay'
999 sub retrieve_hold_queue_stats {
1000 my($self, $conn, $auth, $hold_id) = @_;
1001 my $e = new_editor(authtoken => $auth);
1002 return $e->event unless $e->checkauth;
1003 my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1004 if($e->requestor->id != $hold->usr) {
1005 return $e->event unless $e->allowed('VIEW_HOLD');
1007 return retrieve_hold_queue_status_impl($e, $hold);
1010 sub retrieve_hold_queue_status_impl {
1014 # The holds queue is defined as the distinct set of holds that share at
1015 # least one potential copy with the context hold, plus any holds that
1016 # share the same hold type and target. The latter part exists to
1017 # accomodate holds that currently have no potential copies
1018 my $q_holds = $e->json_query({
1020 # fetch request_time since it's in the order_by and we're asking for distinct values
1021 select => {ahr => ['id', 'request_time']},
1024 ahcm => {type => 'left'} # there may be no copy maps
1027 order_by => {ahr => ['request_time']},
1035 select => {ahcm => ['target_copy']},
1037 where => {hold => $hold->id}
1044 hold_type => $hold->hold_type,
1045 target => $hold->target
1053 for my $h (@$q_holds) {
1054 last if $h->{id} == $hold->id;
1058 my $hold_data = $e->json_query({
1061 {column => 'code', transform => 'count', aggregate => 1, alias => 'count'},
1062 {column =>'avg_wait_time'}
1065 from => {ahcm => {acp => {join => 'ccm'}}},
1066 where => {'+ahcm' => {hold => $hold->id}}
1069 my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1071 my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1072 my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1073 $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1074 $default_wait ||= '0 seconds';
1076 # Estimated wait time is the average wait time across the set
1077 # of potential copies, divided by the number of potential copies
1078 # times the queue position.
1080 my $combined_secs = 0;
1081 my $num_potentials = 0;
1083 for my $wait_data (@$hold_data) {
1084 my $count += $wait_data->{count};
1085 $combined_secs += $count *
1086 OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1087 $num_potentials += $count;
1090 my $estimated_wait = -1;
1092 if($num_potentials) {
1093 my $avg_wait = $combined_secs / $num_potentials;
1094 $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1095 $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1099 total_holds => scalar(@$q_holds),
1100 queue_position => $qpos,
1101 potential_copies => $num_potentials,
1102 status => _hold_status( $e, $hold ),
1103 estimated_wait => int($estimated_wait)
1108 sub fetch_open_hold_by_current_copy {
1111 my $hold = $apputils->simplereq(
1113 'open-ils.cstore.direct.action.hold_request.search.atomic',
1114 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1115 return $hold->[0] if ref($hold);
1119 sub fetch_related_holds {
1122 return $apputils->simplereq(
1124 'open-ils.cstore.direct.action.hold_request.search.atomic',
1125 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1129 __PACKAGE__->register_method(
1130 method => "hold_pull_list",
1131 api_name => "open-ils.circ.hold_pull_list.retrieve",
1133 desc => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1134 'The location is determined by the login session.',
1136 { desc => 'Limit (optional)', type => 'number'},
1137 { desc => 'Offset (optional)', type => 'number'},
1140 desc => 'reference to a list of holds, or event on failure',
1145 __PACKAGE__->register_method(
1146 method => "hold_pull_list",
1147 api_name => "open-ils.circ.hold_pull_list.id_list.retrieve",
1149 desc => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1150 'The location is determined by the login session.',
1152 { desc => 'Limit (optional)', type => 'number'},
1153 { desc => 'Offset (optional)', type => 'number'},
1156 desc => 'reference to a list of holds, or event on failure',
1161 __PACKAGE__->register_method(
1162 method => "hold_pull_list",
1163 api_name => "open-ils.circ.hold_pull_list.retrieve.count",
1165 desc => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1166 'The location is determined by the login session.',
1168 { desc => 'Limit (optional)', type => 'number'},
1169 { desc => 'Offset (optional)', type => 'number'},
1172 desc => 'Holds count (integer), or event on failure',
1179 sub hold_pull_list {
1180 my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1181 my( $reqr, $evt ) = $U->checkses($authtoken);
1182 return $evt if $evt;
1184 my $org = $reqr->ws_ou || $reqr->home_ou;
1185 # the perm locaiton shouldn't really matter here since holds
1186 # will exist all over and VIEW_HOLDS should be universal
1187 $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1188 return $evt if $evt;
1190 if($self->api_name =~ /count/) {
1192 my $count = $U->storagereq(
1193 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1194 $org, $limit, $offset );
1196 $logger->info("Grabbing pull list for org unit $org with $count items");
1199 } elsif( $self->api_name =~ /id_list/ ) {
1200 return $U->storagereq(
1201 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1202 $org, $limit, $offset );
1205 return $U->storagereq(
1206 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1207 $org, $limit, $offset );
1211 __PACKAGE__->register_method(
1212 method => 'fetch_hold_notify',
1213 api_name => 'open-ils.circ.hold_notification.retrieve_by_hold',
1216 Returns a list of hold notification objects based on hold id.
1217 @param authtoken The loggin session key
1218 @param holdid The id of the hold whose notifications we want to retrieve
1219 @return An array of hold notification objects, event on error.
1223 sub fetch_hold_notify {
1224 my( $self, $conn, $authtoken, $holdid ) = @_;
1225 my( $requestor, $evt ) = $U->checkses($authtoken);
1226 return $evt if $evt;
1227 my ($hold, $patron);
1228 ($hold, $evt) = $U->fetch_hold($holdid);
1229 return $evt if $evt;
1230 ($patron, $evt) = $U->fetch_user($hold->usr);
1231 return $evt if $evt;
1233 $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1234 return $evt if $evt;
1236 $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1237 return $U->cstorereq(
1238 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1242 __PACKAGE__->register_method(
1243 method => 'create_hold_notify',
1244 api_name => 'open-ils.circ.hold_notification.create',
1246 Creates a new hold notification object
1247 @param authtoken The login session key
1248 @param notification The hold notification object to create
1249 @return ID of the new object on success, Event on error
1253 sub create_hold_notify {
1254 my( $self, $conn, $auth, $note ) = @_;
1255 my $e = new_editor(authtoken=>$auth, xact=>1);
1256 return $e->die_event unless $e->checkauth;
1258 my $hold = $e->retrieve_action_hold_request($note->hold)
1259 or return $e->die_event;
1260 my $patron = $e->retrieve_actor_user($hold->usr)
1261 or return $e->die_event;
1263 return $e->die_event unless
1264 $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1266 $note->notify_staff($e->requestor->id);
1267 $e->create_action_hold_notification($note) or return $e->die_event;
1272 __PACKAGE__->register_method(
1273 method => 'create_hold_note',
1274 api_name => 'open-ils.circ.hold_note.create',
1276 Creates a new hold request note object
1277 @param authtoken The login session key
1278 @param note The hold note object to create
1279 @return ID of the new object on success, Event on error
1283 sub create_hold_note {
1284 my( $self, $conn, $auth, $note ) = @_;
1285 my $e = new_editor(authtoken=>$auth, xact=>1);
1286 return $e->die_event unless $e->checkauth;
1288 my $hold = $e->retrieve_action_hold_request($note->hold)
1289 or return $e->die_event;
1290 my $patron = $e->retrieve_actor_user($hold->usr)
1291 or return $e->die_event;
1293 return $e->die_event unless
1294 $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn. Probably want something more specific
1296 $e->create_action_hold_request_note($note) or return $e->die_event;
1301 __PACKAGE__->register_method(
1302 method => 'reset_hold',
1303 api_name => 'open-ils.circ.hold.reset',
1305 Un-captures and un-targets a hold, essentially returning
1306 it to the state it was in directly after it was placed,
1307 then attempts to re-target the hold
1308 @param authtoken The login session key
1309 @param holdid The id of the hold
1315 my( $self, $conn, $auth, $holdid ) = @_;
1317 my ($hold, $evt) = $U->fetch_hold($holdid);
1318 return $evt if $evt;
1319 ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1320 return $evt if $evt;
1321 $evt = _reset_hold($self, $reqr, $hold);
1322 return $evt if $evt;
1327 __PACKAGE__->register_method(
1328 method => 'reset_hold_batch',
1329 api_name => 'open-ils.circ.hold.reset.batch'
1332 sub reset_hold_batch {
1333 my($self, $conn, $auth, $hold_ids) = @_;
1335 my $e = new_editor(authtoken => $auth);
1336 return $e->event unless $e->checkauth;
1338 for my $hold_id ($hold_ids) {
1340 my $hold = $e->retrieve_action_hold_request(
1341 [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}])
1342 or return $e->event;
1344 next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1345 _reset_hold($self, $e->requestor, $hold);
1353 my ($self, $reqr, $hold) = @_;
1355 my $e = new_editor(xact =>1, requestor => $reqr);
1357 $logger->info("reseting hold ".$hold->id);
1359 my $hid = $hold->id;
1361 if( $hold->capture_time and $hold->current_copy ) {
1363 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1364 or return $e->event;
1366 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1367 $logger->info("setting copy to status 'reshelving' on hold retarget");
1368 $copy->status(OILS_COPY_STATUS_RESHELVING);
1369 $copy->editor($e->requestor->id);
1370 $copy->edit_date('now');
1371 $e->update_asset_copy($copy) or return $e->event;
1373 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1375 # We don't want the copy to remain "in transit"
1376 $copy->status(OILS_COPY_STATUS_RESHELVING);
1377 $logger->warn("! reseting hold [$hid] that is in transit");
1378 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1381 my $trans = $e->retrieve_action_transit_copy($transid);
1383 $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1384 my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1);
1385 $logger->info("Transit abort completed with result $evt");
1386 return $evt unless "$evt" eq 1;
1392 $hold->clear_capture_time;
1393 $hold->clear_current_copy;
1394 $hold->clear_shelf_time;
1395 $hold->clear_shelf_expire_time;
1397 $e->update_action_hold_request($hold) or return $e->event;
1401 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1407 __PACKAGE__->register_method(
1408 method => 'fetch_open_title_holds',
1409 api_name => 'open-ils.circ.open_holds.retrieve',
1411 Returns a list ids of un-fulfilled holds for a given title id
1412 @param authtoken The login session key
1413 @param id the id of the item whose holds we want to retrieve
1414 @param type The hold type - M, T, V, C
1418 sub fetch_open_title_holds {
1419 my( $self, $conn, $auth, $id, $type, $org ) = @_;
1420 my $e = new_editor( authtoken => $auth );
1421 return $e->event unless $e->checkauth;
1424 $org ||= $e->requestor->ws_ou;
1426 # return $e->search_action_hold_request(
1427 # { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1429 # XXX make me return IDs in the future ^--
1430 my $holds = $e->search_action_hold_request(
1433 cancel_time => undef,
1435 fulfillment_time => undef
1439 flesh_hold_transits($holds);
1444 sub flesh_hold_transits {
1446 for my $hold ( @$holds ) {
1448 $apputils->simplereq(
1450 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1451 { hold => $hold->id },
1452 { order_by => { ahtc => 'id desc' }, limit => 1 }
1458 sub flesh_hold_notices {
1459 my( $holds, $e ) = @_;
1460 $e ||= new_editor();
1462 for my $hold (@$holds) {
1463 my $notices = $e->search_action_hold_notification(
1465 { hold => $hold->id },
1466 { order_by => { anh => 'notify_time desc' } },
1471 $hold->notify_count(scalar(@$notices));
1473 my $n = $e->retrieve_action_hold_notification($$notices[0])
1474 or return $e->event;
1475 $hold->notify_time($n->notify_time);
1481 __PACKAGE__->register_method(
1482 method => 'fetch_captured_holds',
1483 api_name => 'open-ils.circ.captured_holds.on_shelf.retrieve',
1486 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
1487 @param authtoken The login session key
1488 @param org The org id of the location in question
1492 __PACKAGE__->register_method(
1493 method => 'fetch_captured_holds',
1494 api_name => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
1497 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
1498 @param authtoken The login session key
1499 @param org The org id of the location in question
1503 __PACKAGE__->register_method(
1504 method => 'fetch_captured_holds',
1505 api_name => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
1508 Returns list ids of shelf-expired un-fulfilled holds for a given title id
1509 @param authtoken The login session key
1510 @param org The org id of the location in question
1515 sub fetch_captured_holds {
1516 my( $self, $conn, $auth, $org ) = @_;
1518 my $e = new_editor(authtoken => $auth);
1519 return $e->event unless $e->checkauth;
1520 return $e->event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
1522 $org ||= $e->requestor->ws_ou;
1525 select => { ahr => ['id'] },
1530 fkey => 'current_copy'
1535 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
1537 capture_time => { "!=" => undef },
1538 current_copy => { "!=" => undef },
1539 fulfillment_time => undef,
1541 cancel_time => undef,
1545 if($self->api_name =~ /expired/) {
1546 $query->{'where'}->{'+ahr'}->{'shelf_expire_time'} = {'<' => 'now'};
1547 $query->{'where'}->{'+ahr'}->{'shelf_time'} = {'!=' => undef};
1549 my $hold_ids = $e->json_query( $query );
1551 for my $hold_id (@$hold_ids) {
1552 if($self->api_name =~ /id_list/) {
1553 $conn->respond($hold_id->{id});
1557 $e->retrieve_action_hold_request([
1561 flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
1562 order_by => {anh => 'notify_time desc'}
1573 __PACKAGE__->register_method(
1574 method => "check_title_hold",
1575 api_name => "open-ils.circ.title_hold.is_possible",
1577 desc => 'Determines if a hold were to be placed by a given user, ' .
1578 'whether or not said hold would have any potential copies to fulfill it.' .
1579 'The named paramaters of the second argument include: ' .
1580 'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
1581 'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' ,
1583 { desc => 'Authentication token', type => 'string'},
1584 { desc => 'Hash of named parameters', type => 'object'},
1587 desc => 'List of new message IDs (empty if none)',
1593 =head3 check_title_hold (token, hash)
1595 The named fields in the hash are:
1597 patronid - ID of the hold recipient (required)
1598 depth - hold range depth (default 0)
1599 pickup_lib - destination for hold, fallback value for selection_ou
1600 selection_ou - ID of org_unit establishing hard and soft hold boundary settings
1601 titleid - ID (BRN) of the title to be held, required for Title level hold
1602 volume_id - required for Volume level hold
1603 copy_id - required for Copy level hold
1604 mrid - required for Meta-record level hold
1605 hold_type - T,C,V or M for Title, Copy, Volume or Meta-record (default "T")
1607 All key/value pairs are passed on to do_possibility_checks.
1611 # FIXME: better params checking. what other params are required, if any?
1612 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
1613 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still
1614 # used in conditionals, where it may be undefined, causing a warning.
1615 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
1617 sub check_title_hold {
1618 my( $self, $client, $authtoken, $params ) = @_;
1619 my $e = new_editor(authtoken=>$authtoken);
1620 return $e->event unless $e->checkauth;
1622 my %params = %$params;
1623 my $depth = $params{depth} || 0;
1624 my $selection_ou = $params{selection_ou} || $params{pickup_lib};
1626 my $patron = $e->retrieve_actor_user($params{patronid})
1627 or return $e->event;
1629 if( $e->requestor->id ne $patron->id ) {
1630 return $e->event unless
1631 $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
1634 return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
1636 my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
1637 or return $e->event;
1639 my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
1640 my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
1643 my $return_depth = $hard_boundary; # default depth to return on success
1644 if(defined $soft_boundary and $depth < $soft_boundary) {
1645 # work up the tree and as soon as we find a potential copy, use that depth
1646 # also, make sure we don't go past the hard boundary if it exists
1648 # our min boundary is the greater of user-specified boundary or hard boundary
1649 my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?
1650 $hard_boundary : $depth;
1652 my $depth = $soft_boundary;
1653 while($depth >= $min_depth) {
1654 $logger->info("performing hold possibility check with soft boundary $depth");
1655 @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
1657 $return_depth = $depth;
1662 } elsif(defined $hard_boundary and $depth < $hard_boundary) {
1663 # there is no soft boundary, enforce the hard boundary if it exists
1664 $logger->info("performing hold possibility check with hard boundary $hard_boundary");
1665 @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
1667 # no boundaries defined, fall back to user specifed boundary or no boundary
1668 $logger->info("performing hold possibility check with no boundary");
1669 @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
1675 "depth" => $return_depth,
1676 "local_avail" => $status[1]
1678 } elsif ($status[2]) {
1679 my $n = scalar @{$status[2]};
1680 return {"success" => 0, "last_event" => $status[2]->[$n - 1]};
1682 return {"success" => 0};
1686 sub do_possibility_checks {
1687 my($e, $patron, $request_lib, $depth, %params) = @_;
1689 my $titleid = $params{titleid} || "";
1690 my $volid = $params{volume_id};
1691 my $copyid = $params{copy_id};
1692 my $mrid = $params{mrid} || "";
1693 my $pickup_lib = $params{pickup_lib};
1694 my $hold_type = $params{hold_type} || 'T';
1695 my $selection_ou = $params{selection_ou} || $pickup_lib;
1702 if( $hold_type eq OILS_HOLD_TYPE_COPY ) {
1704 return $e->event unless $copy = $e->retrieve_asset_copy($copyid);
1705 return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
1706 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
1708 return verify_copy_for_hold(
1709 $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib
1712 } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
1714 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
1715 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
1717 return _check_volume_hold_is_possible(
1718 $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
1721 } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
1723 return _check_title_hold_is_possible(
1724 $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
1727 } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
1729 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
1730 my @recs = map { $_->source } @$maps;
1732 for my $rec (@recs) {
1733 @status = _check_title_hold_is_possible(
1734 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
1740 # else { Unrecognized hold_type ! } # FIXME: return error? or 0?
1744 sub create_ranged_org_filter {
1745 my($e, $selection_ou, $depth) = @_;
1747 # find the orgs from which this hold may be fulfilled,
1748 # based on the selection_ou and depth
1750 my $top_org = $e->search_actor_org_unit([
1751 {parent_ou => undef},
1752 {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
1755 return () if $depth == $top_org->ou_type->depth;
1757 my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
1758 %org_filter = (circ_lib => []);
1759 push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
1761 $logger->info("hold org filter at depth $depth and selection_ou ".
1762 "$selection_ou created list of @{$org_filter{circ_lib}}");
1768 sub _check_title_hold_is_possible {
1769 my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
1771 my $e = new_editor();
1772 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
1774 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
1775 my $copies = $e->json_query(
1777 select => { acp => ['id', 'circ_lib'] },
1782 fkey => 'call_number',
1786 filter => { id => $titleid },
1791 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
1792 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
1796 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
1801 $logger->info("title possible found ".scalar(@$copies)." potential copies");
1805 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
1806 "payload" => {"fail_part" => "no_ultimate_items"}
1811 # -----------------------------------------------------------------------
1812 # sort the copies into buckets based on their circ_lib proximity to
1813 # the patron's home_ou.
1814 # -----------------------------------------------------------------------
1816 my $home_org = $patron->home_ou;
1817 my $req_org = $request_lib->id;
1819 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
1821 $prox_cache{$home_org} =
1822 $e->search_actor_org_unit_proximity({from_org => $home_org})
1823 unless $prox_cache{$home_org};
1824 my $home_prox = $prox_cache{$home_org};
1827 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
1828 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1830 my @keys = sort { $a <=> $b } keys %buckets;
1833 if( $home_org ne $req_org ) {
1834 # -----------------------------------------------------------------------
1835 # shove the copies close to the request_lib into the primary buckets
1836 # directly before the farthest away copies. That way, they are not
1837 # given priority, but they are checked before the farthest copies.
1838 # -----------------------------------------------------------------------
1839 $prox_cache{$req_org} =
1840 $e->search_actor_org_unit_proximity({from_org => $req_org})
1841 unless $prox_cache{$req_org};
1842 my $req_prox = $prox_cache{$req_org};
1845 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
1846 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1848 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
1849 my $new_key = $highest_key - 0.5; # right before the farthest prox
1850 my @keys2 = sort { $a <=> $b } keys %buckets2;
1851 for my $key (@keys2) {
1852 last if $key >= $highest_key;
1853 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
1857 @keys = sort { $a <=> $b } keys %buckets;
1862 OUTER: for my $key (@keys) {
1863 my @cps = @{$buckets{$key}};
1865 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
1867 for my $copyid (@cps) {
1869 next if $seen{$copyid};
1870 $seen{$copyid} = 1; # there could be dupes given the merged buckets
1871 my $copy = $e->retrieve_asset_copy($copyid);
1872 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
1874 unless($title) { # grab the title if we don't already have it
1875 my $vol = $e->retrieve_asset_call_number(
1876 [ $copy->call_number, { flesh => 1, flesh_fields => { acn => ['record'] } } ] );
1877 $title = $vol->record;
1880 @status = verify_copy_for_hold(
1881 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
1883 last OUTER if $status[0];
1891 sub _check_volume_hold_is_possible {
1892 my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
1893 my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
1894 my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
1895 $logger->info("checking possibility of volume hold for volume ".$vol->id);
1900 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
1901 "payload" => {"fail_part" => "no_ultimate_items"}
1907 for my $copy ( @$copies ) {
1908 @status = verify_copy_for_hold(
1909 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
1917 sub verify_copy_for_hold {
1918 my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib ) = @_;
1919 $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
1920 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
1921 { patron => $patron,
1922 requestor => $requestor,
1925 title_descriptor => $title->fixed_fields, # this is fleshed into the title object
1926 pickup_lib => $pickup_lib,
1927 request_lib => $request_lib,
1929 show_event_list => 1
1934 (not scalar @$permitted), # true if permitted is an empty arrayref
1936 ($copy->circ_lib == $pickup_lib) and
1937 ($copy->status == OILS_COPY_STATUS_AVAILABLE)
1945 sub find_nearest_permitted_hold {
1948 my $editor = shift; # CStoreEditor object
1949 my $copy = shift; # copy to target
1950 my $user = shift; # staff
1951 my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
1953 my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
1955 my $bc = $copy->barcode;
1957 # find any existing holds that already target this copy
1958 my $old_holds = $editor->search_action_hold_request(
1959 { current_copy => $copy->id,
1960 cancel_time => undef,
1961 capture_time => undef
1965 # hold->type "R" means we need this copy
1966 for my $h (@$old_holds) { return ($h) if $h->hold_type eq 'R'; }
1969 my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
1971 $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
1972 " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
1974 # search for what should be the best holds for this copy to fulfill
1975 my $best_holds = $U->storagereq(
1976 "open-ils.storage.action.hold_request.nearest_hold.atomic",
1977 $user->ws_ou, $copy->id, 10, $hold_stall_interval );
1979 unless(@$best_holds) {
1981 if( my $hold = $$old_holds[0] ) {
1982 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
1986 $logger->info("circulator: no suitable holds found for copy $bc");
1987 return (undef, $evt);
1993 # for each potential hold, we have to run the permit script
1994 # to make sure the hold is actually permitted.
1995 for my $holdid (@$best_holds) {
1996 next unless $holdid;
1997 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
1999 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
2000 my $reqr = $editor->retrieve_actor_user($hold->requestor) or next;
2001 my $rlib = $editor->retrieve_actor_org_unit($hold->request_lib) or next;
2003 # see if this hold is permitted
2004 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2005 { patron_id => $hold->usr,
2008 pickup_lib => $hold->pickup_lib,
2009 request_lib => $rlib,
2020 unless( $best_hold ) { # no "good" permitted holds were found
2021 if( my $hold = $$old_holds[0] ) { # can we return a pre-targeted hold?
2022 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2027 $logger->info("circulator: no suitable holds found for copy $bc");
2028 return (undef, $evt);
2031 $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
2033 # indicate a permitted hold was found
2034 return $best_hold if $check_only;
2036 # we've found a permitted hold. we need to "grab" the copy
2037 # to prevent re-targeted holds (next part) from re-grabbing the copy
2038 $best_hold->current_copy($copy->id);
2039 $editor->update_action_hold_request($best_hold)
2040 or return (undef, $editor->event);
2045 # re-target any other holds that already target this copy
2046 for my $old_hold (@$old_holds) {
2047 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
2048 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
2049 $old_hold->id." after a better hold [".$best_hold->id."] was found");
2050 $old_hold->clear_current_copy;
2051 $old_hold->clear_prev_check_time;
2052 $editor->update_action_hold_request($old_hold)
2053 or return (undef, $editor->event);
2054 push(@retarget, $old_hold->id);
2057 return ($best_hold, undef, (@retarget) ? \@retarget : undef);
2065 __PACKAGE__->register_method(
2066 method => 'all_rec_holds',
2067 api_name => 'open-ils.circ.holds.retrieve_all_from_title',
2071 my( $self, $conn, $auth, $title_id, $args ) = @_;
2073 my $e = new_editor(authtoken=>$auth);
2074 $e->checkauth or return $e->event;
2075 $e->allowed('VIEW_HOLD') or return $e->event;
2078 $args->{fulfillment_time} = undef; # we don't want to see old fulfilled holds
2079 $args->{cancel_time} = undef;
2081 my $resp = { volume_holds => [], copy_holds => [], metarecord_holds => [] };
2083 my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
2085 $resp->{metarecord_holds} = $e->search_action_hold_request(
2086 { hold_type => OILS_HOLD_TYPE_METARECORD,
2087 target => $mr_map->metarecord,
2093 $resp->{title_holds} = $e->search_action_hold_request(
2095 hold_type => OILS_HOLD_TYPE_TITLE,
2096 target => $title_id,
2100 my $vols = $e->search_asset_call_number(
2101 { record => $title_id, deleted => 'f' }, {idlist=>1});
2103 return $resp unless @$vols;
2105 $resp->{volume_holds} = $e->search_action_hold_request(
2107 hold_type => OILS_HOLD_TYPE_VOLUME,
2112 my $copies = $e->search_asset_copy(
2113 { call_number => $vols, deleted => 'f' }, {idlist=>1});
2115 return $resp unless @$copies;
2117 $resp->{copy_holds} = $e->search_action_hold_request(
2119 hold_type => OILS_HOLD_TYPE_COPY,
2131 __PACKAGE__->register_method(
2132 method => 'uber_hold',
2134 api_name => 'open-ils.circ.hold.details.retrieve'
2138 my($self, $client, $auth, $hold_id) = @_;
2139 my $e = new_editor(authtoken=>$auth);
2140 $e->checkauth or return $e->event;
2141 return uber_hold_impl($e, $hold_id);
2144 __PACKAGE__->register_method(
2145 method => 'batch_uber_hold',
2148 api_name => 'open-ils.circ.hold.details.batch.retrieve'
2151 sub batch_uber_hold {
2152 my($self, $client, $auth, $hold_ids) = @_;
2153 my $e = new_editor(authtoken=>$auth);
2154 $e->checkauth or return $e->event;
2155 $client->respond(uber_hold_impl($e, $_)) for @$hold_ids;
2159 sub uber_hold_impl {
2160 my($e, $hold_id) = @_;
2164 my $hold = $e->retrieve_action_hold_request(
2169 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
2172 ) or return $e->event;
2174 if($hold->usr->id ne $e->requestor->id) {
2175 # A user is allowed to see his/her own holds
2176 $e->allowed('VIEW_HOLD') or return $e->event;
2177 $hold->notes( # filter out any non-staff ("private") notes
2178 [ grep { !$U->is_true($_->staff) } @{$hold->notes} ] );
2181 # caller is asking for own hold, but may not have permission to view staff notes
2182 unless($e->allowed('VIEW_HOLD')) {
2183 $hold->notes( # filter out any staff notes
2184 [ grep { $U->is_true($_->staff) } @{$hold->notes} ] );
2188 my $user = $hold->usr;
2189 $hold->usr($user->id);
2191 my $card = $e->retrieve_actor_card($user->card)
2192 or return $e->event;
2194 my( $mvr, $volume, $copy ) = find_hold_mvr($e, $hold);
2196 flesh_hold_notices([$hold], $e);
2197 flesh_hold_transits([$hold]);
2199 my $details = retrieve_hold_queue_status_impl($e, $hold);
2206 patron_first => $user->first_given_name,
2207 patron_last => $user->family_name,
2208 patron_barcode => $card->barcode,
2215 # -----------------------------------------------------
2216 # Returns the MVR object that represents what the
2218 # -----------------------------------------------------
2220 my( $e, $hold ) = @_;
2226 if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2227 my $mr = $e->retrieve_metabib_metarecord($hold->target)
2228 or return $e->event;
2229 $tid = $mr->master_record;
2231 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
2232 $tid = $hold->target;
2234 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2235 $volume = $e->retrieve_asset_call_number($hold->target)
2236 or return $e->event;
2237 $tid = $volume->record;
2239 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_COPY ) {
2240 $copy = $e->retrieve_asset_copy($hold->target)
2241 or return $e->event;
2242 $volume = $e->retrieve_asset_call_number($copy->call_number)
2243 or return $e->event;
2244 $tid = $volume->record;
2247 if(!$copy and ref $hold->current_copy ) {
2248 $copy = $hold->current_copy;
2249 $hold->current_copy($copy->id);
2252 if(!$volume and $copy) {
2253 $volume = $e->retrieve_asset_call_number($copy->call_number);
2256 # TODO return metarcord mvr for M holds
2257 my $title = $e->retrieve_biblio_record_entry($tid);
2258 return ( $U->record_to_mvr($title), $volume, $copy );
2262 __PACKAGE__->register_method(
2263 method => 'clear_shelf_process',
2265 api_name => 'open-ils.circ.hold.clear_shelf.process',
2268 1. Find all holds that have expired on the holds shelf
2270 3. If a clear-shelf status is configured, put targeted copies into this status
2271 4. Divide copies into 3 groups: items to transit, items to reshelve, and items
2272 that are needed for holds. No subsequent action is taken on the holds
2273 or items after grouping.
2278 sub clear_shelf_process {
2279 my($self, $client, $auth, $org_id) = @_;
2281 my $e = new_editor(authtoken=>$auth, xact => 1);
2282 $e->checkauth or return $e->die_event;
2284 $org_id ||= $e->requestor->ws_ou;
2285 $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
2287 my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
2289 # Find holds on the shelf that have been there too long
2290 my $hold_ids = $e->search_action_hold_request(
2291 { shelf_expire_time => {'<' => 'now'},
2292 pickup_lib => $org_id,
2293 cancel_time => undef,
2294 fulfillment_time => undef,
2295 shelf_time => {'!=' => undef}
2302 for my $hold_id (@$hold_ids) {
2304 $logger->info("Clear shelf processing hold $hold_id");
2306 my $hold = $e->retrieve_action_hold_request([
2309 flesh_fields => {ahr => ['current_copy']}
2313 $hold->cancel_time('now');
2314 $hold->cancel_cause(2); # Hold Shelf expiration
2315 $e->update_action_hold_request($hold) or return $e->die_event;
2317 my $copy = $hold->current_copy;
2319 if($copy_status or $copy_status == 0) {
2320 # if a clear-shelf copy status is defined, update the copy
2321 $copy->status($copy_status);
2322 $copy->edit_date('now');
2323 $copy->editor($e->requestor->id);
2324 $e->update_asset_copy($copy) or return $e->die_event;
2327 push(@holds, $hold);
2332 for my $hold (@holds) {
2334 my $copy = $hold->current_copy;
2336 my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
2340 # copy is needed for a hold
2341 $client->respond({action => 'hold', copy => $copy, hold_id => $hold->id});
2343 } elsif($copy->circ_lib != $e->requestor->ws_ou) {
2345 # copy needs to transit
2346 $client->respond({action => 'transit', copy => $copy, hold_id => $hold->id});
2350 # copy needs to go back to the shelf
2351 $client->respond({action => 'shelf', copy => $copy, hold_id => $hold->id});
2355 # tell the client we're done
2356 $client->respond_complete;
2358 # fire off the hold cancelation trigger
2359 my $trigger = OpenSRF::AppSession->connect('open-ils.trigger');
2361 for my $hold (@holds) {
2363 my $req = $trigger->request(
2364 'open-ils.trigger.event.autocreate',
2365 'hold_request.cancel.expire_holds_shelf',
2368 # wait for response so don't flood the service
2372 $trigger->disconnect;
2375 # tell the client we're done
2376 $client->respond_complete;
2380 __PACKAGE__->register_method(
2381 method => 'usr_hold_summary',
2382 api_name => 'open-ils.circ.holds.user_summary',
2384 Returns a summary of holds statuses for a given user
2388 sub usr_hold_summary {
2389 my($self, $conn, $auth, $user_id) = @_;
2391 my $e = new_editor(authtoken=>$auth);
2392 $e->checkauth or return $e->event;
2393 $e->allowed('VIEW_HOLD') or return $e->event;
2395 my $holds = $e->search_action_hold_request(
2398 fulfillment_time => undef,
2399 cancel_time => undef,
2403 my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
2404 $summary{_hold_status($e, $_)} += 1 for @$holds;
2410 __PACKAGE__->register_method(
2411 method => 'hold_has_copy_at',
2412 api_name => 'open-ils.circ.hold.has_copy_at',
2415 'Returns the ID of the found copy and name of the shelving location if there is ' .
2416 'an available copy at the specified org unit. Returns empty hash otherwise. ' .
2417 'The anticipated use for this method is to determine whether an item is ' .
2418 'available at the library where the user is placing the hold (or, alternatively, '.
2419 'at the pickup library) to encourage bypassing the hold placement and just ' .
2420 'checking out the item.' ,
2422 { desc => 'Authentication Token', type => 'string' },
2423 { desc => 'Method Arguments. Options include: hold_type, hold_target, org_unit. '
2424 . 'hold_type is the hold type code (T, V, C, M, ...). '
2425 . 'hold_target is the identifier of the hold target object. '
2426 . 'org_unit is org unit ID.',
2431 desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
2437 sub hold_has_copy_at {
2438 my($self, $conn, $auth, $args) = @_;
2440 my $e = new_editor(authtoken=>$auth);
2441 $e->checkauth or return $e->event;
2443 my $hold_type = $$args{hold_type};
2444 my $hold_target = $$args{hold_target};
2445 my $org_unit = $$args{org_unit};
2448 select => {acp => ['id'], acpl => ['name']},
2451 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
2452 ccs => {field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2455 where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit}},
2459 if($hold_type eq 'C') {
2461 $query->{where}->{'+acp'}->{id} = $hold_target;
2463 } elsif($hold_type eq 'V') {
2465 $query->{where}->{'+acp'}->{call_number} = $hold_target;
2467 } elsif($hold_type eq 'T') {
2469 $query->{from}->{acp}->{acn} = {
2471 fkey => 'call_number',
2475 filter => {id => $hold_target},
2483 $query->{from}->{acp}->{acn} = {
2485 fkey => 'call_number',
2494 filter => {metarecord => $hold_target},
2502 my $res = $e->json_query($query)->[0] or return {};
2503 return {copy => $res->{id}, location => $res->{name}} if $res;
2507 # returns true if the user already has an item checked out
2508 # that could be used to fulfill the requested hold.
2509 sub hold_item_is_checked_out {
2510 my($e, $user_id, $hold_type, $hold_target) = @_;
2513 select => {acp => ['id']},
2514 from => {acp => {}},
2518 in => { # copies for circs the user has checked out
2519 select => {circ => ['target_copy']},
2523 checkin_time => undef,
2525 {stop_fines => ["MAXFINES","LONGOVERDUE"]},
2526 {stop_fines => undef}
2536 if($hold_type eq 'C') {
2538 $query->{where}->{'+acp'}->{id}->{in}->{where}->{'target_copy'} = $hold_target;
2540 } elsif($hold_type eq 'V') {
2542 $query->{where}->{'+acp'}->{call_number} = $hold_target;
2544 } elsif($hold_type eq 'T') {
2546 $query->{from}->{acp}->{acn} = {
2548 fkey => 'call_number',
2552 filter => {id => $hold_target},
2560 $query->{from}->{acp}->{acn} = {
2562 fkey => 'call_number',
2571 filter => {metarecord => $hold_target},
2579 return $e->json_query($query)->[0];
2582 __PACKAGE__->register_method(
2583 method => 'change_hold_title',
2584 api_name => 'open-ils.circ.hold.change_title',
2587 Updates all title level holds targeting the specified bibs to point a new bib./,
2589 { desc => 'Authentication Token', type => 'string' },
2590 { desc => 'New Target Bib Id', type => 'number' },
2591 { desc => 'Old Target Bib Ids', type => 'array' },
2593 return => { desc => '1 on success' }
2597 sub change_hold_title {
2598 my( $self, $client, $auth, $new_bib_id, $bib_ids ) = @_;
2600 my $e = new_editor(authtoken=>$auth, xact=>1);
2601 return $e->event unless $e->checkauth;
2603 my $holds = $e->search_action_hold_request(
2606 cancel_time => undef,
2607 fulfillment_time => undef,
2613 flesh_fields => { ahr => ['usr'] }
2619 for my $hold (@$holds) {
2620 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
2621 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
2622 $hold->target( $new_bib_id );
2623 $e->update_action_hold_request($hold) or return $e->die_event;
2632 __PACKAGE__->register_method(
2633 method => 'rec_hold_count',
2634 api_name => 'open-ils.circ.bre.holds.count',
2636 desc => q/Returns the total number of holds that target the
2637 selected bib record or its associated copies and call_numbers/,
2639 { desc => 'Bib ID', type => 'number' },
2641 return => {desc => 'Hold count', type => 'number'}
2645 __PACKAGE__->register_method(
2646 method => 'rec_hold_count',
2647 api_name => 'open-ils.circ.mmr.holds.count',
2649 desc => q/Returns the total number of holds that target the
2650 selected metarecord or its associated copies, call_numbers, and bib records/,
2652 { desc => 'Metarecord ID', type => 'number' },
2654 return => {desc => 'Hold count', type => 'number'}
2658 sub rec_hold_count {
2659 my($self, $conn, $target_id) = @_;
2666 filter => {metarecord => $target_id}
2673 filter => { id => $target_id },
2678 if($self->api_name =~ /mmr/) {
2679 delete $bre_join->{bre}->{filter};
2680 $bre_join->{bre}->{join} = $mmr_join;
2686 fkey => 'call_number',
2692 select => {ahr => [{column => 'id', transform => 'count', alias => 'count'}]},
2696 cancel_time => undef,
2697 fulfillment_time => undef,
2704 select => {acp => ['id']},
2705 from => { acp => $cn_join }
2715 select => {acn => ['id']},
2716 from => {acn => $bre_join}
2724 target => $target_id
2732 if($self->api_name =~ /mmr/) {
2733 $query->{where}->{'+ahr'}->{'-or'}->[2] = {
2738 select => {bre => ['id']},
2739 from => {bre => $mmr_join}
2745 $query->{where}->{'+ahr'}->{'-or'}->[3] = {
2748 target => $target_id
2754 return new_editor()->json_query($query)->[0]->{count};