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 use Digest::MD5 qw(md5_hex);
38 use OpenSRF::Utils::Cache;
39 use OpenSRF::Utils::JSON;
40 my $apputils = "OpenILS::Application::AppUtils";
43 __PACKAGE__->register_method(
44 method => "test_and_create_hold_batch",
45 api_name => "open-ils.circ.holds.test_and_create.batch",
48 desc => q/This is for batch creating a set of holds where every field is identical except for the targets./,
50 { desc => 'Authentication token', type => 'string' },
51 { desc => 'Hash of named parameters. Same as for open-ils.circ.title_hold.is_possible, though the pertinent target field is automatically populated based on the hold_type and the specified list of targets.', type => 'object'},
52 { desc => 'Array of target ids', type => 'array' }
55 desc => 'Array of hold ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
60 __PACKAGE__->register_method(
61 method => "test_and_create_hold_batch",
62 api_name => "open-ils.circ.holds.test_and_create.batch.override",
65 desc => '@see open-ils.circ.holds.test_and_create.batch',
70 sub test_and_create_hold_batch {
71 my( $self, $conn, $auth, $params, $target_list, $oargs ) = @_;
74 if ($self->api_name =~ /override/) {
76 $oargs = { all => 1 } unless defined $oargs;
77 $$params{oargs} = $oargs; # for is_possible checking.
80 my $e = new_editor(authtoken=>$auth);
81 return $e->die_event unless $e->checkauth;
82 $$params{'requestor'} = $e->requestor->id;
85 if ($$params{'hold_type'} eq 'T') { $target_field = 'titleid'; }
86 elsif ($$params{'hold_type'} eq 'C') { $target_field = 'copy_id'; }
87 elsif ($$params{'hold_type'} eq 'R') { $target_field = 'copy_id'; }
88 elsif ($$params{'hold_type'} eq 'F') { $target_field = 'copy_id'; }
89 elsif ($$params{'hold_type'} eq 'I') { $target_field = 'issuanceid'; }
90 elsif ($$params{'hold_type'} eq 'V') { $target_field = 'volume_id'; }
91 elsif ($$params{'hold_type'} eq 'M') { $target_field = 'mrid'; }
92 elsif ($$params{'hold_type'} eq 'P') { $target_field = 'partid'; }
93 else { return undef; }
95 foreach (@$target_list) {
96 $$params{$target_field} = $_;
98 ($res) = $self->method_lookup(
99 'open-ils.circ.title_hold.is_possible')->run($auth, $params, $override ? $oargs : {});
100 if ($res->{'success'} == 1) {
102 $params->{'depth'} = $res->{'depth'} if $res->{'depth'};
104 # Remove oargs from params so holds can be created.
105 if ($$params{oargs}) {
106 delete $$params{oargs};
109 my $ahr = construct_hold_request_object($params);
110 my ($res2) = $self->method_lookup(
112 ? 'open-ils.circ.holds.create.override'
113 : 'open-ils.circ.holds.create'
114 )->run($auth, $ahr, $oargs);
116 'target' => $$params{$target_field},
119 $conn->respond($res2);
122 'target' => $$params{$target_field},
125 $conn->respond($res);
131 sub construct_hold_request_object {
134 my $ahr = Fieldmapper::action::hold_request->new;
137 foreach my $field (keys %{ $params }) {
138 if ($field eq 'depth') { $ahr->selection_depth($$params{$field}); }
139 elsif ($field eq 'patronid') {
140 $ahr->usr($$params{$field}); }
141 elsif ($field eq 'titleid') { $ahr->target($$params{$field}); }
142 elsif ($field eq 'copy_id') { $ahr->target($$params{$field}); }
143 elsif ($field eq 'issuanceid') { $ahr->target($$params{$field}); }
144 elsif ($field eq 'volume_id') { $ahr->target($$params{$field}); }
145 elsif ($field eq 'mrid') { $ahr->target($$params{$field}); }
146 elsif ($field eq 'partid') { $ahr->target($$params{$field}); }
148 $ahr->$field($$params{$field});
154 __PACKAGE__->register_method(
155 method => "create_hold_batch",
156 api_name => "open-ils.circ.holds.create.batch",
159 desc => q/@see open-ils.circ.holds.create.batch/,
161 { desc => 'Authentication token', type => 'string' },
162 { desc => 'Array of hold objects', type => 'array' }
165 desc => 'Array of hold ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
170 __PACKAGE__->register_method(
171 method => "create_hold_batch",
172 api_name => "open-ils.circ.holds.create.override.batch",
175 desc => '@see open-ils.circ.holds.create.batch',
180 sub create_hold_batch {
181 my( $self, $conn, $auth, $hold_list, $oargs ) = @_;
182 (my $method = $self->api_name) =~ s/\.batch//og;
183 foreach (@$hold_list) {
184 my ($res) = $self->method_lookup($method)->run($auth, $_, $oargs);
185 $conn->respond($res);
191 __PACKAGE__->register_method(
192 method => "create_hold",
193 api_name => "open-ils.circ.holds.create",
195 desc => "Create a new hold for an item. From a permissions perspective, " .
196 "the login session is used as the 'requestor' of the hold. " .
197 "The hold recipient is determined by the 'usr' setting within the hold object. " .
198 'First we verify the requestor has holds request permissions. ' .
199 'Then we verify that the recipient is allowed to make the given hold. ' .
200 'If not, we see if the requestor has "override" capabilities. If not, ' .
201 'a permission exception is returned. If permissions allow, we cycle ' .
202 'through the set of holds objects and create. ' .
203 'If the recipient does not have permission to place multiple holds ' .
204 'on a single title and said operation is attempted, a permission ' .
205 'exception is returned',
207 { desc => 'Authentication token', type => 'string' },
208 { desc => 'Hold object for hold to be created',
209 type => 'object', class => 'ahr' }
212 desc => 'New ahr ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
217 __PACKAGE__->register_method(
218 method => "create_hold",
219 api_name => "open-ils.circ.holds.create.override",
220 notes => '@see open-ils.circ.holds.create',
222 desc => "If the recipient is not allowed to receive the requested hold, " .
223 "call this method to attempt the override",
225 { desc => 'Authentication token', type => 'string' },
227 desc => 'Hold object for hold to be created',
228 type => 'object', class => 'ahr'
232 desc => 'New hold (ahr) ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
238 my( $self, $conn, $auth, $hold, $oargs ) = @_;
239 return -1 unless $hold;
240 my $e = new_editor(authtoken=>$auth, xact=>1);
241 return $e->die_event unless $e->checkauth;
244 if ($self->api_name =~ /override/) {
246 $oargs = { all => 1 } unless defined $oargs;
251 my $requestor = $e->requestor;
252 my $recipient = $requestor;
254 if( $requestor->id ne $hold->usr ) {
255 # Make sure the requestor is allowed to place holds for
256 # the recipient if they are not the same people
257 $recipient = $e->retrieve_actor_user($hold->usr) or return $e->die_event;
258 $e->allowed('REQUEST_HOLDS', $recipient->home_ou) or return $e->die_event;
261 # If the related org setting tells us to, block if patron privs have expired
262 my $expire_setting = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_BLOCK_HOLD_FOR_EXPIRED_PATRON);
263 if ($expire_setting) {
264 my $expire = DateTime::Format::ISO8601->new->parse_datetime(
265 cleanse_ISO8601($recipient->expire_date));
267 push( @events, OpenILS::Event->new(
268 'PATRON_ACCOUNT_EXPIRED',
269 "payload" => {"fail_part" => "actor.usr.privs_expired"}
270 )) if( CORE::time > $expire->epoch ) ;
273 # Now make sure the recipient is allowed to receive the specified hold
274 my $porg = $recipient->home_ou;
275 my $rid = $e->requestor->id;
276 my $t = $hold->hold_type;
278 # See if a duplicate hold already exists
280 usr => $recipient->id,
282 fulfillment_time => undef,
283 target => $hold->target,
284 cancel_time => undef,
287 $sargs->{holdable_formats} = $hold->holdable_formats if $t eq 'M';
289 my $existing = $e->search_action_hold_request($sargs);
290 push( @events, OpenILS::Event->new('HOLD_EXISTS')) if @$existing;
292 my $checked_out = hold_item_is_checked_out($e, $recipient->id, $hold->hold_type, $hold->target);
293 push( @events, OpenILS::Event->new('HOLD_ITEM_CHECKED_OUT')) if $checked_out;
295 if ( $t eq OILS_HOLD_TYPE_METARECORD ) {
296 return $e->die_event unless $e->allowed('MR_HOLDS', $porg);
297 } elsif ( $t eq OILS_HOLD_TYPE_TITLE ) {
298 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
299 } elsif ( $t eq OILS_HOLD_TYPE_VOLUME ) {
300 return $e->die_event unless $e->allowed('VOLUME_HOLDS', $porg);
301 } elsif ( $t eq OILS_HOLD_TYPE_MONOPART ) {
302 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
303 } elsif ( $t eq OILS_HOLD_TYPE_ISSUANCE ) {
304 return $e->die_event unless $e->allowed('ISSUANCE_HOLDS', $porg);
305 } elsif ( $t eq OILS_HOLD_TYPE_COPY ) {
306 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
307 } elsif ( $t eq OILS_HOLD_TYPE_FORCE || $t eq OILS_HOLD_TYPE_RECALL ) {
308 my $copy = $e->retrieve_asset_copy($hold->target)
309 or return $e->die_event;
310 if ( $t eq OILS_HOLD_TYPE_FORCE ) {
311 return $e->die_event unless $e->allowed('COPY_HOLDS_FORCE', $copy->circ_lib);
312 } elsif ( $t eq OILS_HOLD_TYPE_RECALL ) {
313 return $e->die_event unless $e->allowed('COPY_HOLDS_RECALL', $copy->circ_lib);
322 for my $evt (@events) {
324 my $name = $evt->{textcode};
325 if($oargs->{all} || grep { $_ eq $name } @{$oargs->{events}}) {
326 return $e->die_event unless $e->allowed("$name.override", $porg);
334 # Check for hold expiration in the past, and set it to empty string.
335 $hold->expire_time(undef) if ($hold->expire_time && $U->datecmp($hold->expire_time) == -1);
337 # set the configured expire time
338 unless($hold->expire_time) {
339 $hold->expire_time(calculate_expire_time($recipient->home_ou));
343 # if behind-the-desk pickup is supported at the hold pickup lib,
344 # set the value to the patron default, unless a value has already
345 # been applied. If it's not supported, force the value to false.
347 my $bdous = $U->ou_ancestor_setting_value(
349 'circ.holds.behind_desk_pickup_supported', $e);
352 if (!defined $hold->behind_desk) {
354 my $set = $e->search_actor_user_setting({
356 name => 'circ.holds_behind_desk'
359 $hold->behind_desk('t') if $set and
360 OpenSRF::Utils::JSON->JSON2perl($set->value);
363 # behind the desk not supported, force it to false
364 $hold->behind_desk('f');
367 $hold->requestor($e->requestor->id);
368 $hold->request_lib($e->requestor->ws_ou);
369 $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
370 $hold = $e->create_action_hold_request($hold) or return $e->die_event;
374 $conn->respond_complete($hold->id);
377 'open-ils.storage.action.hold_request.copy_targeter',
378 undef, $hold->id ) unless $U->is_true($hold->frozen);
383 # makes sure that a user has permission to place the type of requested hold
384 # returns the Perm exception if not allowed, returns undef if all is well
385 sub _check_holds_perm {
386 my($type, $user_id, $org_id) = @_;
390 $evt = $apputils->check_perms($user_id, $org_id, "MR_HOLDS" );
391 } elsif ($type eq "T") {
392 $evt = $apputils->check_perms($user_id, $org_id, "TITLE_HOLDS" );
393 } elsif($type eq "V") {
394 $evt = $apputils->check_perms($user_id, $org_id, "VOLUME_HOLDS");
395 } elsif($type eq "C") {
396 $evt = $apputils->check_perms($user_id, $org_id, "COPY_HOLDS" );
403 # tests if the given user is allowed to place holds on another's behalf
404 sub _check_request_holds_perm {
407 if (my $evt = $apputils->check_perms(
408 $user_id, $org_id, "REQUEST_HOLDS")) {
413 my $ses_is_req_note = 'The login session is the requestor. If the requestor is different from the user, ' .
414 'then the requestor must have VIEW_HOLD permissions';
416 __PACKAGE__->register_method(
417 method => "retrieve_holds_by_id",
418 api_name => "open-ils.circ.holds.retrieve_by_id",
420 desc => "Retrieve the hold, with hold transits attached, for the specified ID. $ses_is_req_note",
422 { desc => 'Authentication token', type => 'string' },
423 { desc => 'Hold ID', type => 'number' }
426 desc => 'Hold object with transits attached, event on error',
432 sub retrieve_holds_by_id {
433 my($self, $client, $auth, $hold_id) = @_;
434 my $e = new_editor(authtoken=>$auth);
435 $e->checkauth or return $e->event;
436 $e->allowed('VIEW_HOLD') or return $e->event;
438 my $holds = $e->search_action_hold_request(
440 { id => $hold_id , fulfillment_time => undef },
442 order_by => { ahr => "request_time" },
444 flesh_fields => {ahr => ['notes']}
449 flesh_hold_transits($holds);
450 flesh_hold_notices($holds, $e);
455 __PACKAGE__->register_method(
456 method => "retrieve_holds",
457 api_name => "open-ils.circ.holds.retrieve",
459 desc => "Retrieves all the holds, with hold transits attached, for the specified user. $ses_is_req_note",
461 { desc => 'Authentication token', type => 'string' },
462 { desc => 'User ID', type => 'integer' },
463 { desc => 'Available Only', type => 'boolean' }
466 desc => 'list of holds, event on error',
471 __PACKAGE__->register_method(
472 method => "retrieve_holds",
473 api_name => "open-ils.circ.holds.id_list.retrieve",
476 desc => "Retrieves all the hold IDs, for the specified user. $ses_is_req_note",
478 { desc => 'Authentication token', type => 'string' },
479 { desc => 'User ID', type => 'integer' },
480 { desc => 'Available Only', type => 'boolean' }
483 desc => 'list of holds, event on error',
488 __PACKAGE__->register_method(
489 method => "retrieve_holds",
490 api_name => "open-ils.circ.holds.canceled.retrieve",
493 desc => "Retrieves all the cancelled holds for the specified user. $ses_is_req_note",
495 { desc => 'Authentication token', type => 'string' },
496 { desc => 'User ID', type => 'integer' }
499 desc => 'list of holds, event on error',
504 __PACKAGE__->register_method(
505 method => "retrieve_holds",
506 api_name => "open-ils.circ.holds.canceled.id_list.retrieve",
509 desc => "Retrieves list of cancelled hold IDs for the specified user. $ses_is_req_note",
511 { desc => 'Authentication token', type => 'string' },
512 { desc => 'User ID', type => 'integer' }
515 desc => 'list of hold IDs, event on error',
522 my ($self, $client, $auth, $user_id, $available) = @_;
524 my $e = new_editor(authtoken=>$auth);
525 return $e->event unless $e->checkauth;
526 $user_id = $e->requestor->id unless defined $user_id;
528 my $notes_filter = {staff => 'f'};
529 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
530 unless($user_id == $e->requestor->id) {
531 if($e->allowed('VIEW_HOLD', $user->home_ou)) {
532 $notes_filter = {staff => 't'}
534 my $allowed = OpenILS::Application::Actor::Friends->friend_perm_allowed(
535 $e, $user_id, $e->requestor->id, 'hold.view');
536 return $e->event unless $allowed;
539 # staff member looking at his/her own holds can see staff and non-staff notes
540 $notes_filter = {} if $e->allowed('VIEW_HOLD', $user->home_ou);
544 select => {ahr => ['id']},
546 where => {usr => $user_id, fulfillment_time => undef}
549 if($self->api_name =~ /canceled/) {
551 # Fetch the canceled holds
552 # order cancelled holds by cancel time, most recent first
554 $holds_query->{order_by} = [{class => 'ahr', field => 'cancel_time', direction => 'desc'}];
557 my $cancel_count = $U->ou_ancestor_setting_value(
558 $e->requestor->ws_ou, 'circ.holds.canceled.display_count', $e);
560 unless($cancel_count) {
561 $cancel_age = $U->ou_ancestor_setting_value(
562 $e->requestor->ws_ou, 'circ.holds.canceled.display_age', $e);
564 # if no settings are defined, default to last 10 cancelled holds
565 $cancel_count = 10 unless $cancel_age;
568 if($cancel_count) { # limit by count
570 $holds_query->{where}->{cancel_time} = {'!=' => undef};
571 $holds_query->{limit} = $cancel_count;
573 } elsif($cancel_age) { # limit by age
575 # find all of the canceled holds that were canceled within the configured time frame
576 my $date = DateTime->now->subtract(seconds => OpenSRF::Utils::interval_to_seconds($cancel_age));
577 $date = $U->epoch2ISO8601($date->epoch);
578 $holds_query->{where}->{cancel_time} = {'>=' => $date};
583 # order non-cancelled holds by ready-for-pickup, then active, followed by suspended
584 # "compare" sorts false values to the front. testing pickup_lib != current_shelf_lib
585 # will sort by pl = csl > pl != csl > followed by csl is null;
586 $holds_query->{order_by} = [
588 field => 'pickup_lib',
589 compare => {'!=' => {'+ahr' => 'current_shelf_lib'}}},
590 {class => 'ahr', field => 'shelf_time'},
591 {class => 'ahr', field => 'frozen'},
592 {class => 'ahr', field => 'request_time'}
595 $holds_query->{where}->{cancel_time} = undef;
597 $holds_query->{where}->{shelf_time} = {'!=' => undef};
599 $holds_query->{where}->{pickup_lib} = {'=' => {'+ahr' => 'current_shelf_lib'}};
603 my $hold_ids = $e->json_query($holds_query);
604 $hold_ids = [ map { $_->{id} } @$hold_ids ];
606 return $hold_ids if $self->api_name =~ /id_list/;
609 for my $hold_id ( @$hold_ids ) {
611 my $hold = $e->retrieve_action_hold_request($hold_id);
612 $hold->notes($e->search_action_hold_request_note({hold => $hold_id, %$notes_filter}));
615 $e->search_action_hold_transit_copy([
617 {order_by => {ahtc => 'source_send_time desc'}, limit => 1}])->[0]
627 __PACKAGE__->register_method(
628 method => 'user_hold_count',
629 api_name => 'open-ils.circ.hold.user.count'
632 sub user_hold_count {
633 my ( $self, $conn, $auth, $userid ) = @_;
634 my $e = new_editor( authtoken => $auth );
635 return $e->event unless $e->checkauth;
636 my $patron = $e->retrieve_actor_user($userid)
638 return $e->event unless $e->allowed( 'VIEW_HOLD', $patron->home_ou );
639 return __user_hold_count( $self, $e, $userid );
642 sub __user_hold_count {
643 my ( $self, $e, $userid ) = @_;
644 my $holds = $e->search_action_hold_request(
647 fulfillment_time => undef,
648 cancel_time => undef,
653 return scalar(@$holds);
657 __PACKAGE__->register_method(
658 method => "retrieve_holds_by_pickup_lib",
659 api_name => "open-ils.circ.holds.retrieve_by_pickup_lib",
661 "Retrieves all the holds, with hold transits attached, for the specified pickup_ou id."
664 __PACKAGE__->register_method(
665 method => "retrieve_holds_by_pickup_lib",
666 api_name => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
667 notes => "Retrieves all the hold ids for the specified pickup_ou id. "
670 sub retrieve_holds_by_pickup_lib {
671 my ($self, $client, $login_session, $ou_id) = @_;
673 #FIXME -- put an appropriate permission check here
674 #my( $user, $target, $evt ) = $apputils->checkses_requestor(
675 # $login_session, $user_id, 'VIEW_HOLD' );
676 #return $evt if $evt;
678 my $holds = $apputils->simplereq(
680 "open-ils.cstore.direct.action.hold_request.search.atomic",
682 pickup_lib => $ou_id ,
683 fulfillment_time => undef,
686 { order_by => { ahr => "request_time" } }
689 if ( ! $self->api_name =~ /id_list/ ) {
690 flesh_hold_transits($holds);
694 return [ map { $_->id } @$holds ];
698 __PACKAGE__->register_method(
699 method => "uncancel_hold",
700 api_name => "open-ils.circ.hold.uncancel"
704 my($self, $client, $auth, $hold_id) = @_;
705 my $e = new_editor(authtoken=>$auth, xact=>1);
706 return $e->die_event unless $e->checkauth;
708 my $hold = $e->retrieve_action_hold_request($hold_id)
709 or return $e->die_event;
710 return $e->die_event unless $e->allowed('CANCEL_HOLDS', $hold->request_lib);
712 if ($hold->fulfillment_time) {
716 unless ($hold->cancel_time) {
721 # if configured to reset the request time, also reset the expire time
722 if($U->ou_ancestor_setting_value(
723 $hold->request_lib, 'circ.holds.uncancel.reset_request_time', $e)) {
725 $hold->request_time('now');
726 $hold->expire_time(calculate_expire_time($hold->request_lib));
729 $hold->clear_cancel_time;
730 $hold->clear_cancel_cause;
731 $hold->clear_cancel_note;
732 $hold->clear_shelf_time;
733 $hold->clear_current_copy;
734 $hold->clear_capture_time;
735 $hold->clear_prev_check_time;
736 $hold->clear_shelf_expire_time;
737 $hold->clear_current_shelf_lib;
739 $e->update_action_hold_request($hold) or return $e->die_event;
742 $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
748 __PACKAGE__->register_method(
749 method => "cancel_hold",
750 api_name => "open-ils.circ.hold.cancel",
752 desc => 'Cancels the specified hold. The login session is the requestor. If the requestor is different from the usr field ' .
753 'on the hold, the requestor must have CANCEL_HOLDS permissions. The hold may be either the hold object or the hold id',
755 {desc => 'Authentication token', type => 'string'},
756 {desc => 'Hold ID', type => 'number'},
757 {desc => 'Cause of Cancellation', type => 'string'},
758 {desc => 'Note', type => 'string'}
761 desc => '1 on success, event on error'
767 my($self, $client, $auth, $holdid, $cause, $note) = @_;
769 my $e = new_editor(authtoken=>$auth, xact=>1);
770 return $e->die_event unless $e->checkauth;
772 my $hold = $e->retrieve_action_hold_request($holdid)
773 or return $e->die_event;
775 if( $e->requestor->id ne $hold->usr ) {
776 return $e->die_event unless $e->allowed('CANCEL_HOLDS');
779 if ($hold->cancel_time) {
784 # If the hold is captured, reset the copy status
785 if( $hold->capture_time and $hold->current_copy ) {
787 my $copy = $e->retrieve_asset_copy($hold->current_copy)
788 or return $e->die_event;
790 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
791 $logger->info("canceling hold $holdid whose item is on the holds shelf");
792 # $logger->info("setting copy to status 'reshelving' on hold cancel");
793 # $copy->status(OILS_COPY_STATUS_RESHELVING);
794 # $copy->editor($e->requestor->id);
795 # $copy->edit_date('now');
796 # $e->update_asset_copy($copy) or return $e->event;
798 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
801 $logger->warn("! canceling hold [$hid] that is in transit");
802 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
805 my $trans = $e->retrieve_action_transit_copy($transid);
806 # Leave the transit alive, but set the copy status to
807 # reshelving so it will be properly reshelved when it gets back home
809 $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
810 $e->update_action_transit_copy($trans) or return $e->die_event;
816 $hold->cancel_time('now');
817 $hold->cancel_cause($cause);
818 $hold->cancel_note($note);
819 $e->update_action_hold_request($hold)
820 or return $e->die_event;
822 delete_hold_copy_maps($self, $e, $hold->id);
826 # re-fetch the hold to pick up the real cancel_time (not "now") for A/T
828 $hold = $e->retrieve_action_hold_request($hold->id) or return $e->die_event;
831 if ($e->requestor->id == $hold->usr) {
832 $U->create_events_for_hook('hold_request.cancel.patron', $hold, $hold->pickup_lib);
834 $U->create_events_for_hook('hold_request.cancel.staff', $hold, $hold->pickup_lib);
840 sub delete_hold_copy_maps {
845 my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
847 $editor->delete_action_hold_copy_map($_)
848 or return $editor->event;
854 my $update_hold_desc = 'The login session is the requestor. ' .
855 'If the requestor is different from the usr field on the hold, ' .
856 'the requestor must have UPDATE_HOLDS permissions. ' .
857 'If supplying a hash of hold data, "id" must be included. ' .
858 'The hash is ignored if a hold object is supplied, ' .
859 'so you should supply only one kind of hold data argument.' ;
861 __PACKAGE__->register_method(
862 method => "update_hold",
863 api_name => "open-ils.circ.hold.update",
865 desc => "Updates the specified hold. $update_hold_desc",
867 {desc => 'Authentication token', type => 'string'},
868 {desc => 'Hold Object', type => 'object'},
869 {desc => 'Hash of values to be applied', type => 'object'}
872 desc => 'Hold ID on success, event on error',
878 __PACKAGE__->register_method(
879 method => "batch_update_hold",
880 api_name => "open-ils.circ.hold.update.batch",
883 desc => "Updates the specified hold(s). $update_hold_desc",
885 {desc => 'Authentication token', type => 'string'},
886 {desc => 'Array of hold obejcts', type => 'array' },
887 {desc => 'Array of hashes of values to be applied', type => 'array' }
890 desc => 'Hold ID per success, event per error',
896 my($self, $client, $auth, $hold, $values) = @_;
897 my $e = new_editor(authtoken=>$auth, xact=>1);
898 return $e->die_event unless $e->checkauth;
899 my $resp = update_hold_impl($self, $e, $hold, $values);
900 if ($U->event_code($resp)) {
904 $e->commit; # FIXME: update_hold_impl already does $e->commit ??
908 sub batch_update_hold {
909 my($self, $client, $auth, $hold_list, $values_list) = @_;
910 my $e = new_editor(authtoken=>$auth);
911 return $e->die_event unless $e->checkauth;
913 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.
915 $values_list ||= []; # FIXME: either move this above $count declaration, or send an event if both lists undef. Probably the latter.
917 # FIXME: Failing over to [] guarantees warnings for "Use of unitialized value" in update_hold_impl call.
918 # FIXME: We should be sure we only call update_hold_impl with hold object OR hash, not both.
920 for my $idx (0..$count-1) {
922 my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
923 $e->xact_commit unless $U->event_code($resp);
924 $client->respond($resp);
928 return undef; # not in the register return type, assuming we should always have at least one list populated
931 sub update_hold_impl {
932 my($self, $e, $hold, $values) = @_;
934 my $need_retarget = 0;
937 $hold = $e->retrieve_action_hold_request($values->{id})
938 or return $e->die_event;
939 for my $k (keys %$values) {
940 # Outside of pickup_lib (covered by the first regex) I don't know when these would currently change.
941 # But hey, why not cover things that may happen later?
942 if ($k =~ '_(lib|ou)$' || $k eq 'target' || $k eq 'hold_type' || $k eq 'requestor' || $k eq 'selection_depth' || $k eq 'holdable_formats') {
943 if (defined $values->{$k} && defined $hold->$k() && $values->{$k} ne $hold->$k()) {
944 # Value changed? RETARGET!
946 } elsif (defined $hold->$k() != defined $values->{$k}) {
947 # Value being set or cleared? RETARGET!
951 if (defined $values->{$k}) {
952 $hold->$k($values->{$k});
954 my $f = "clear_$k"; $hold->$f();
959 my $orig_hold = $e->retrieve_action_hold_request($hold->id)
960 or return $e->die_event;
962 # don't allow the user to be changed
963 return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
965 if($hold->usr ne $e->requestor->id) {
966 # if the hold is for a different user, make sure the
967 # requestor has the appropriate permissions
968 my $usr = $e->retrieve_actor_user($hold->usr)
969 or return $e->die_event;
970 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
974 # --------------------------------------------------------------
975 # Changing the request time is like playing God
976 # --------------------------------------------------------------
977 if($hold->request_time ne $orig_hold->request_time) {
978 return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
979 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
983 # --------------------------------------------------------------
984 # Code for making sure staff have appropriate permissons for cut_in_line
985 # This, as is, doesn't prevent a user from cutting their own holds in line
987 # --------------------------------------------------------------
988 if($U->is_true($hold->cut_in_line) ne $U->is_true($orig_hold->cut_in_line)) {
989 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
993 # --------------------------------------------------------------
994 # Disallow hold suspencion if the hold is already captured.
995 # --------------------------------------------------------------
996 if ($U->is_true($hold->frozen) and not $U->is_true($orig_hold->frozen)) {
997 $hold_status = _hold_status($e, $hold);
998 if ($hold_status > 2 && $hold_status != 7) { # hold is captured
999 $logger->info("bypassing hold freeze on captured hold");
1000 return OpenILS::Event->new('HOLD_SUSPEND_AFTER_CAPTURE');
1005 # --------------------------------------------------------------
1006 # if the hold is on the holds shelf or in transit and the pickup
1007 # lib changes we need to create a new transit.
1008 # --------------------------------------------------------------
1009 if($orig_hold->pickup_lib ne $hold->pickup_lib) {
1011 $hold_status = _hold_status($e, $hold) unless $hold_status;
1013 if($hold_status == 3) { # in transit
1015 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
1016 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
1018 $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
1020 # update the transit to reflect the new pickup location
1021 my $transit = $e->search_action_hold_transit_copy(
1022 {hold=>$hold->id, dest_recv_time => undef})->[0]
1023 or return $e->die_event;
1025 $transit->prev_dest($transit->dest); # mark the previous destination on the transit
1026 $transit->dest($hold->pickup_lib);
1027 $e->update_action_hold_transit_copy($transit) or return $e->die_event;
1029 } elsif($hold_status == 4 or $hold_status == 5 or $hold_status == 8) { # on holds shelf
1031 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
1032 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
1034 $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
1036 if ($hold->pickup_lib eq $orig_hold->current_shelf_lib) {
1037 # This can happen if the pickup lib is changed while the hold is
1038 # on the shelf, then changed back to the original pickup lib.
1039 # Restore the original shelf_expire_time to prevent abuse.
1040 set_hold_shelf_expire_time(undef, $hold, $e, $hold->shelf_time);
1043 # clear to prevent premature shelf expiration
1044 $hold->clear_shelf_expire_time;
1049 if($U->is_true($hold->frozen)) {
1050 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
1051 $hold->clear_current_copy;
1052 $hold->clear_prev_check_time;
1053 # Clear expire_time to prevent frozen holds from expiring.
1054 $logger->info("clearing expire_time for frozen hold ".$hold->id);
1055 $hold->clear_expire_time;
1058 # If the hold_expire_time is in the past && is not equal to the
1059 # original expire_time, then reset the expire time to be in the
1061 if ($hold->expire_time && $U->datecmp($hold->expire_time) == -1 && $U->datecmp($hold->expire_time, $orig_hold->expire_time) != 0) {
1062 $hold->expire_time(calculate_expire_time($hold->request_lib));
1065 # If the hold is reactivated, reset the expire_time.
1066 if(!$U->is_true($hold->frozen) && $U->is_true($orig_hold->frozen)) {
1067 $logger->info("Reset expire_time on activated hold ".$hold->id);
1068 $hold->expire_time(calculate_expire_time($hold->request_lib));
1071 $e->update_action_hold_request($hold) or return $e->die_event;
1074 if(!$U->is_true($hold->frozen) && $U->is_true($orig_hold->frozen)) {
1075 $logger->info("Running targeter on activated hold ".$hold->id);
1076 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1079 # a change to mint-condition changes the set of potential copies, so retarget the hold;
1080 if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
1081 _reset_hold($self, $e->requestor, $hold)
1082 } elsif($need_retarget && !defined $hold->capture_time()) { # If needed, retarget the hold due to changes
1084 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1090 # this does not update the hold in the DB. It only
1091 # sets the shelf_expire_time field on the hold object.
1092 # start_time is optional and defaults to 'now'
1093 sub set_hold_shelf_expire_time {
1094 my ($class, $hold, $editor, $start_time) = @_;
1096 my $shelf_expire = $U->ou_ancestor_setting_value(
1098 'circ.holds.default_shelf_expire_interval',
1102 return undef unless $shelf_expire;
1104 $start_time = ($start_time) ?
1105 DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time)) :
1108 my $seconds = OpenSRF::Utils->interval_to_seconds($shelf_expire);
1109 my $expire_time = $start_time->add(seconds => $seconds);
1111 # if the shelf expire time overlaps with a pickup lib's
1112 # closed date, push it out to the first open date
1113 my $dateinfo = $U->storagereq(
1114 'open-ils.storage.actor.org_unit.closed_date.overlap',
1115 $hold->pickup_lib, $expire_time->strftime('%FT%T%z'));
1118 my $dt_parser = DateTime::Format::ISO8601->new;
1119 $expire_time = $dt_parser->parse_datetime(cleanse_ISO8601($dateinfo->{end}));
1121 # TODO: enable/disable time bump via setting?
1122 $expire_time->set(hour => '23', minute => '59', second => '59');
1124 $logger->info("circulator: shelf_expire_time overlaps".
1125 " with closed date, pushing expire time to $expire_time");
1128 $hold->shelf_expire_time($expire_time->strftime('%FT%T%z'));
1134 my($e, $orig_hold, $hold, $copy) = @_;
1135 my $src = $orig_hold->pickup_lib;
1136 my $dest = $hold->pickup_lib;
1138 $logger->info("putting hold into transit on pickup_lib update");
1140 my $transit = Fieldmapper::action::hold_transit_copy->new;
1141 $transit->hold($hold->id);
1142 $transit->source($src);
1143 $transit->dest($dest);
1144 $transit->target_copy($copy->id);
1145 $transit->source_send_time('now');
1146 $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
1148 $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
1149 $copy->editor($e->requestor->id);
1150 $copy->edit_date('now');
1152 $e->create_action_hold_transit_copy($transit) or return $e->die_event;
1153 $e->update_asset_copy($copy) or return $e->die_event;
1157 # if the hold is frozen, this method ensures that the hold is not "targeted",
1158 # that is, it clears the current_copy and prev_check_time to essentiallly
1159 # reset the hold. If it is being activated, it runs the targeter in the background
1160 sub update_hold_if_frozen {
1161 my($self, $e, $hold, $orig_hold) = @_;
1162 return if $hold->capture_time;
1164 if($U->is_true($hold->frozen)) {
1165 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
1166 $hold->clear_current_copy;
1167 $hold->clear_prev_check_time;
1170 if($U->is_true($orig_hold->frozen)) {
1171 $logger->info("Running targeter on activated hold ".$hold->id);
1172 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1177 __PACKAGE__->register_method(
1178 method => "hold_note_CUD",
1179 api_name => "open-ils.circ.hold_request.note.cud",
1181 desc => 'Create, update or delete a hold request note. If the operator (from Auth. token) '
1182 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
1184 { desc => 'Authentication token', type => 'string' },
1185 { desc => 'Hold note object', type => 'object' }
1188 desc => 'Returns the note ID, event on error'
1194 my($self, $conn, $auth, $note) = @_;
1196 my $e = new_editor(authtoken => $auth, xact => 1);
1197 return $e->die_event unless $e->checkauth;
1199 my $hold = $e->retrieve_action_hold_request($note->hold)
1200 or return $e->die_event;
1202 if($hold->usr ne $e->requestor->id) {
1203 my $usr = $e->retrieve_actor_user($hold->usr);
1204 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
1205 $note->staff('t') if $note->isnew;
1209 $e->create_action_hold_request_note($note) or return $e->die_event;
1210 } elsif($note->ischanged) {
1211 $e->update_action_hold_request_note($note) or return $e->die_event;
1212 } elsif($note->isdeleted) {
1213 $e->delete_action_hold_request_note($note) or return $e->die_event;
1221 __PACKAGE__->register_method(
1222 method => "retrieve_hold_status",
1223 api_name => "open-ils.circ.hold.status.retrieve",
1225 desc => 'Calculates the current status of the hold. The requestor must have ' .
1226 'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
1228 { desc => 'Hold ID', type => 'number' }
1231 # type => 'number', # event sometimes
1232 desc => <<'END_OF_DESC'
1233 Returns event on error or:
1234 -1 on error (for now),
1235 1 for 'waiting for copy to become available',
1236 2 for 'waiting for copy capture',
1239 5 for 'hold-shelf-delay'
1242 8 for 'captured, on wrong hold shelf'
1248 sub retrieve_hold_status {
1249 my($self, $client, $auth, $hold_id) = @_;
1251 my $e = new_editor(authtoken => $auth);
1252 return $e->event unless $e->checkauth;
1253 my $hold = $e->retrieve_action_hold_request($hold_id)
1254 or return $e->event;
1256 if( $e->requestor->id != $hold->usr ) {
1257 return $e->event unless $e->allowed('VIEW_HOLD');
1260 return _hold_status($e, $hold);
1266 if ($hold->cancel_time) {
1269 if ($U->is_true($hold->frozen) && !$hold->capture_time) {
1272 if ($hold->current_shelf_lib and $hold->current_shelf_lib ne $hold->pickup_lib) {
1275 return 1 unless $hold->current_copy;
1276 return 2 unless $hold->capture_time;
1278 my $copy = $hold->current_copy;
1279 unless( ref $copy ) {
1280 $copy = $e->retrieve_asset_copy($hold->current_copy)
1281 or return $e->event;
1284 return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
1286 if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
1288 my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
1289 return 4 unless $hs_wait_interval;
1291 # if a hold_shelf_status_delay interval is defined and start_time plus
1292 # the interval is greater than now, consider the hold to be in the virtual
1293 # "on its way to the holds shelf" status. Return 5.
1295 my $transit = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
1296 my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
1297 $start_time = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
1298 my $end_time = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
1300 return 5 if $end_time > DateTime->now;
1309 __PACKAGE__->register_method(
1310 method => "retrieve_hold_queue_stats",
1311 api_name => "open-ils.circ.hold.queue_stats.retrieve",
1313 desc => 'Returns summary data about the state of a hold',
1315 { desc => 'Authentication token', type => 'string'},
1316 { desc => 'Hold ID', type => 'number'},
1319 desc => q/Summary object with keys:
1320 total_holds : total holds in queue
1321 queue_position : current queue position
1322 potential_copies : number of potential copies for this hold
1323 estimated_wait : estimated wait time in days
1324 status : hold status
1325 -1 => error or unexpected state,
1326 1 => 'waiting for copy to become available',
1327 2 => 'waiting for copy capture',
1330 5 => 'hold-shelf-delay'
1337 sub retrieve_hold_queue_stats {
1338 my($self, $conn, $auth, $hold_id) = @_;
1339 my $e = new_editor(authtoken => $auth);
1340 return $e->event unless $e->checkauth;
1341 my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1342 if($e->requestor->id != $hold->usr) {
1343 return $e->event unless $e->allowed('VIEW_HOLD');
1345 return retrieve_hold_queue_status_impl($e, $hold);
1348 sub retrieve_hold_queue_status_impl {
1352 # The holds queue is defined as the distinct set of holds that share at
1353 # least one potential copy with the context hold, plus any holds that
1354 # share the same hold type and target. The latter part exists to
1355 # accomodate holds that currently have no potential copies
1356 my $q_holds = $e->json_query({
1358 # fetch cut_in_line and request_time since they're in the order_by
1359 # and we're asking for distinct values
1360 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1364 select => { ahcm => ['hold'] },
1369 'field' => 'target_copy',
1370 'fkey' => 'target_copy'
1374 where => { '+ahcm2' => { hold => $hold->id } },
1381 "field" => "cut_in_line",
1382 "transform" => "coalesce",
1384 "direction" => "desc"
1386 { "class" => "ahr", "field" => "request_time" }
1391 if (!@$q_holds) { # none? maybe we don't have a map ...
1392 $q_holds = $e->json_query({
1393 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1398 "field" => "cut_in_line",
1399 "transform" => "coalesce",
1401 "direction" => "desc"
1403 { "class" => "ahr", "field" => "request_time" }
1406 hold_type => $hold->hold_type,
1407 target => $hold->target,
1408 capture_time => undef,
1409 cancel_time => undef,
1411 {expire_time => undef },
1412 {expire_time => {'>' => 'now'}}
1420 for my $h (@$q_holds) {
1421 last if $h->{id} == $hold->id;
1425 my $hold_data = $e->json_query({
1427 acp => [ {column => 'id', transform => 'count', aggregate => 1, alias => 'count'} ],
1428 ccm => [ {column =>'avg_wait_time'} ]
1434 ccm => {type => 'left'}
1439 where => {'+ahcm' => {hold => $hold->id} }
1442 my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1444 my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1445 my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1446 $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1447 $default_wait ||= '0 seconds';
1449 # Estimated wait time is the average wait time across the set
1450 # of potential copies, divided by the number of potential copies
1451 # times the queue position.
1453 my $combined_secs = 0;
1454 my $num_potentials = 0;
1456 for my $wait_data (@$hold_data) {
1457 my $count += $wait_data->{count};
1458 $combined_secs += $count *
1459 OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1460 $num_potentials += $count;
1463 my $estimated_wait = -1;
1465 if($num_potentials) {
1466 my $avg_wait = $combined_secs / $num_potentials;
1467 $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1468 $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1472 total_holds => scalar(@$q_holds),
1473 queue_position => $qpos,
1474 potential_copies => $num_potentials,
1475 status => _hold_status( $e, $hold ),
1476 estimated_wait => int($estimated_wait)
1481 sub fetch_open_hold_by_current_copy {
1484 my $hold = $apputils->simplereq(
1486 'open-ils.cstore.direct.action.hold_request.search.atomic',
1487 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1488 return $hold->[0] if ref($hold);
1492 sub fetch_related_holds {
1495 return $apputils->simplereq(
1497 'open-ils.cstore.direct.action.hold_request.search.atomic',
1498 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1502 __PACKAGE__->register_method(
1503 method => "hold_pull_list",
1504 api_name => "open-ils.circ.hold_pull_list.retrieve",
1506 desc => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1507 'The location is determined by the login session.',
1509 { desc => 'Limit (optional)', type => 'number'},
1510 { desc => 'Offset (optional)', type => 'number'},
1513 desc => 'reference to a list of holds, or event on failure',
1518 __PACKAGE__->register_method(
1519 method => "hold_pull_list",
1520 api_name => "open-ils.circ.hold_pull_list.id_list.retrieve",
1522 desc => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1523 'The location is determined by the login session.',
1525 { desc => 'Limit (optional)', type => 'number'},
1526 { desc => 'Offset (optional)', type => 'number'},
1529 desc => 'reference to a list of holds, or event on failure',
1534 __PACKAGE__->register_method(
1535 method => "hold_pull_list",
1536 api_name => "open-ils.circ.hold_pull_list.retrieve.count",
1538 desc => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1539 'The location is determined by the login session.',
1541 { desc => 'Limit (optional)', type => 'number'},
1542 { desc => 'Offset (optional)', type => 'number'},
1545 desc => 'Holds count (integer), or event on failure',
1552 sub hold_pull_list {
1553 my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1554 my( $reqr, $evt ) = $U->checkses($authtoken);
1555 return $evt if $evt;
1557 my $org = $reqr->ws_ou || $reqr->home_ou;
1558 # the perm locaiton shouldn't really matter here since holds
1559 # will exist all over and VIEW_HOLDS should be universal
1560 $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1561 return $evt if $evt;
1563 if($self->api_name =~ /count/) {
1565 my $count = $U->storagereq(
1566 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1567 $org, $limit, $offset );
1569 $logger->info("Grabbing pull list for org unit $org with $count items");
1572 } elsif( $self->api_name =~ /id_list/ ) {
1573 return $U->storagereq(
1574 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1575 $org, $limit, $offset );
1578 return $U->storagereq(
1579 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1580 $org, $limit, $offset );
1584 __PACKAGE__->register_method(
1585 method => "print_hold_pull_list",
1586 api_name => "open-ils.circ.hold_pull_list.print",
1588 desc => 'Returns an HTML-formatted holds pull list',
1590 { desc => 'Authtoken', type => 'string'},
1591 { desc => 'Org unit ID. Optional, defaults to workstation org unit', type => 'number'},
1594 desc => 'HTML string',
1600 sub print_hold_pull_list {
1601 my($self, $client, $auth, $org_id) = @_;
1603 my $e = new_editor(authtoken=>$auth);
1604 return $e->event unless $e->checkauth;
1606 $org_id = (defined $org_id) ? $org_id : $e->requestor->ws_ou;
1607 return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1609 my $hold_ids = $U->storagereq(
1610 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1613 return undef unless @$hold_ids;
1615 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1617 # Holds will /NOT/ be in order after this ...
1618 my $holds = $e->search_action_hold_request({id => $hold_ids}, {substream => 1});
1619 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1621 # ... so we must resort.
1622 my $hold_map = +{map { $_->id => $_ } @$holds};
1623 my $sorted_holds = [];
1624 push @$sorted_holds, $hold_map->{$_} foreach @$hold_ids;
1626 return $U->fire_object_event(
1627 undef, "ahr.format.pull_list", $sorted_holds,
1628 $org_id, undef, undef, $client
1633 __PACKAGE__->register_method(
1634 method => "print_hold_pull_list_stream",
1636 api_name => "open-ils.circ.hold_pull_list.print.stream",
1638 desc => 'Returns a stream of fleshed holds',
1640 { desc => 'Authtoken', type => 'string'},
1641 { desc => 'Hash of optional param: Org unit ID (defaults to workstation org unit), limit, offset, sort (array of: acplo.position, prefix, call_number, suffix, request_time)',
1646 desc => 'A stream of fleshed holds',
1652 sub print_hold_pull_list_stream {
1653 my($self, $client, $auth, $params) = @_;
1655 my $e = new_editor(authtoken=>$auth);
1656 return $e->die_event unless $e->checkauth;
1658 delete($$params{org_id}) unless (int($$params{org_id}));
1659 delete($$params{limit}) unless (int($$params{limit}));
1660 delete($$params{offset}) unless (int($$params{offset}));
1661 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1662 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1663 $$params{chunk_size} ||= 10;
1665 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1666 return $e->die_event unless $e->allowed('VIEW_HOLD', $$params{org_id });
1669 if ($$params{sort} && @{ $$params{sort} }) {
1670 for my $s (@{ $$params{sort} }) {
1671 if ($s eq 'acplo.position') {
1673 "class" => "acplo", "field" => "position",
1674 "transform" => "coalesce", "params" => [999]
1676 } elsif ($s eq 'prefix') {
1677 push @$sort, {"class" => "acnp", "field" => "label_sortkey"};
1678 } elsif ($s eq 'call_number') {
1679 push @$sort, {"class" => "acn", "field" => "label_sortkey"};
1680 } elsif ($s eq 'suffix') {
1681 push @$sort, {"class" => "acns", "field" => "label_sortkey"};
1682 } elsif ($s eq 'request_time') {
1683 push @$sort, {"class" => "ahr", "field" => "request_time"};
1687 push @$sort, {"class" => "ahr", "field" => "request_time"};
1690 my $holds_ids = $e->json_query(
1692 "select" => {"ahr" => ["id"]},
1697 "fkey" => "current_copy",
1699 "circ_lib" => $$params{org_id}, "status" => [0,7]
1704 "fkey" => "call_number",
1718 "fkey" => "circ_lib",
1721 "location" => {"=" => {"+acp" => "location"}}
1730 "capture_time" => undef,
1731 "cancel_time" => undef,
1733 {"expire_time" => undef },
1734 {"expire_time" => {">" => "now"}}
1738 (@$sort ? (order_by => $sort) : ()),
1739 ($$params{limit} ? (limit => $$params{limit}) : ()),
1740 ($$params{offset} ? (offset => $$params{offset}) : ())
1741 }, {"substream" => 1}
1742 ) or return $e->die_event;
1744 $logger->info("about to stream back " . scalar(@$holds_ids) . " holds");
1747 for my $hid (@$holds_ids) {
1748 push @chunk, $e->retrieve_action_hold_request([
1752 "ahr" => ["usr", "current_copy"],
1754 "acp" => ["location", "call_number", "parts"],
1755 "acn" => ["record","prefix","suffix"]
1760 if (@chunk >= $$params{chunk_size}) {
1761 $client->respond( \@chunk );
1765 $client->respond_complete( \@chunk ) if (@chunk);
1772 __PACKAGE__->register_method(
1773 method => 'fetch_hold_notify',
1774 api_name => 'open-ils.circ.hold_notification.retrieve_by_hold',
1777 Returns a list of hold notification objects based on hold id.
1778 @param authtoken The loggin session key
1779 @param holdid The id of the hold whose notifications we want to retrieve
1780 @return An array of hold notification objects, event on error.
1784 sub fetch_hold_notify {
1785 my( $self, $conn, $authtoken, $holdid ) = @_;
1786 my( $requestor, $evt ) = $U->checkses($authtoken);
1787 return $evt if $evt;
1788 my ($hold, $patron);
1789 ($hold, $evt) = $U->fetch_hold($holdid);
1790 return $evt if $evt;
1791 ($patron, $evt) = $U->fetch_user($hold->usr);
1792 return $evt if $evt;
1794 $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1795 return $evt if $evt;
1797 $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1798 return $U->cstorereq(
1799 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1803 __PACKAGE__->register_method(
1804 method => 'create_hold_notify',
1805 api_name => 'open-ils.circ.hold_notification.create',
1807 Creates a new hold notification object
1808 @param authtoken The login session key
1809 @param notification The hold notification object to create
1810 @return ID of the new object on success, Event on error
1814 sub create_hold_notify {
1815 my( $self, $conn, $auth, $note ) = @_;
1816 my $e = new_editor(authtoken=>$auth, xact=>1);
1817 return $e->die_event unless $e->checkauth;
1819 my $hold = $e->retrieve_action_hold_request($note->hold)
1820 or return $e->die_event;
1821 my $patron = $e->retrieve_actor_user($hold->usr)
1822 or return $e->die_event;
1824 return $e->die_event unless
1825 $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1827 $note->notify_staff($e->requestor->id);
1828 $e->create_action_hold_notification($note) or return $e->die_event;
1833 __PACKAGE__->register_method(
1834 method => 'create_hold_note',
1835 api_name => 'open-ils.circ.hold_note.create',
1837 Creates a new hold request note object
1838 @param authtoken The login session key
1839 @param note The hold note object to create
1840 @return ID of the new object on success, Event on error
1844 sub create_hold_note {
1845 my( $self, $conn, $auth, $note ) = @_;
1846 my $e = new_editor(authtoken=>$auth, xact=>1);
1847 return $e->die_event unless $e->checkauth;
1849 my $hold = $e->retrieve_action_hold_request($note->hold)
1850 or return $e->die_event;
1851 my $patron = $e->retrieve_actor_user($hold->usr)
1852 or return $e->die_event;
1854 return $e->die_event unless
1855 $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn. Probably want something more specific
1857 $e->create_action_hold_request_note($note) or return $e->die_event;
1862 __PACKAGE__->register_method(
1863 method => 'reset_hold',
1864 api_name => 'open-ils.circ.hold.reset',
1866 Un-captures and un-targets a hold, essentially returning
1867 it to the state it was in directly after it was placed,
1868 then attempts to re-target the hold
1869 @param authtoken The login session key
1870 @param holdid The id of the hold
1876 my( $self, $conn, $auth, $holdid ) = @_;
1878 my ($hold, $evt) = $U->fetch_hold($holdid);
1879 return $evt if $evt;
1880 ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1881 return $evt if $evt;
1882 $evt = _reset_hold($self, $reqr, $hold);
1883 return $evt if $evt;
1888 __PACKAGE__->register_method(
1889 method => 'reset_hold_batch',
1890 api_name => 'open-ils.circ.hold.reset.batch'
1893 sub reset_hold_batch {
1894 my($self, $conn, $auth, $hold_ids) = @_;
1896 my $e = new_editor(authtoken => $auth);
1897 return $e->event unless $e->checkauth;
1899 for my $hold_id ($hold_ids) {
1901 my $hold = $e->retrieve_action_hold_request(
1902 [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}])
1903 or return $e->event;
1905 next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1906 _reset_hold($self, $e->requestor, $hold);
1914 my ($self, $reqr, $hold) = @_;
1916 my $e = new_editor(xact =>1, requestor => $reqr);
1918 $logger->info("reseting hold ".$hold->id);
1920 my $hid = $hold->id;
1922 if( $hold->capture_time and $hold->current_copy ) {
1924 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1925 or return $e->die_event;
1927 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1928 $logger->info("setting copy to status 'reshelving' on hold retarget");
1929 $copy->status(OILS_COPY_STATUS_RESHELVING);
1930 $copy->editor($e->requestor->id);
1931 $copy->edit_date('now');
1932 $e->update_asset_copy($copy) or return $e->die_event;
1934 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1936 # We don't want the copy to remain "in transit"
1937 $copy->status(OILS_COPY_STATUS_RESHELVING);
1938 $logger->warn("! reseting hold [$hid] that is in transit");
1939 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1942 my $trans = $e->retrieve_action_transit_copy($transid);
1944 $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1945 my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1, 1);
1946 $logger->info("Transit abort completed with result $evt");
1947 unless ("$evt" eq 1) {
1956 $hold->clear_capture_time;
1957 $hold->clear_current_copy;
1958 $hold->clear_shelf_time;
1959 $hold->clear_shelf_expire_time;
1960 $hold->clear_current_shelf_lib;
1962 $e->update_action_hold_request($hold) or return $e->die_event;
1966 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1972 __PACKAGE__->register_method(
1973 method => 'fetch_open_title_holds',
1974 api_name => 'open-ils.circ.open_holds.retrieve',
1976 Returns a list ids of un-fulfilled holds for a given title id
1977 @param authtoken The login session key
1978 @param id the id of the item whose holds we want to retrieve
1979 @param type The hold type - M, T, I, V, C, F, R
1983 sub fetch_open_title_holds {
1984 my( $self, $conn, $auth, $id, $type, $org ) = @_;
1985 my $e = new_editor( authtoken => $auth );
1986 return $e->event unless $e->checkauth;
1989 $org ||= $e->requestor->ws_ou;
1991 # return $e->search_action_hold_request(
1992 # { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1994 # XXX make me return IDs in the future ^--
1995 my $holds = $e->search_action_hold_request(
1998 cancel_time => undef,
2000 fulfillment_time => undef
2004 flesh_hold_transits($holds);
2009 sub flesh_hold_transits {
2011 for my $hold ( @$holds ) {
2013 $apputils->simplereq(
2015 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
2016 { hold => $hold->id },
2017 { order_by => { ahtc => 'id desc' }, limit => 1 }
2023 sub flesh_hold_notices {
2024 my( $holds, $e ) = @_;
2025 $e ||= new_editor();
2027 for my $hold (@$holds) {
2028 my $notices = $e->search_action_hold_notification(
2030 { hold => $hold->id },
2031 { order_by => { anh => 'notify_time desc' } },
2036 $hold->notify_count(scalar(@$notices));
2038 my $n = $e->retrieve_action_hold_notification($$notices[0])
2039 or return $e->event;
2040 $hold->notify_time($n->notify_time);
2046 __PACKAGE__->register_method(
2047 method => 'fetch_captured_holds',
2048 api_name => 'open-ils.circ.captured_holds.on_shelf.retrieve',
2052 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
2053 @param authtoken The login session key
2054 @param org The org id of the location in question
2055 @param match_copy A specific copy to limit to
2059 __PACKAGE__->register_method(
2060 method => 'fetch_captured_holds',
2061 api_name => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
2065 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
2066 @param authtoken The login session key
2067 @param org The org id of the location in question
2068 @param match_copy A specific copy to limit to
2072 __PACKAGE__->register_method(
2073 method => 'fetch_captured_holds',
2074 api_name => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
2078 Returns list ids of shelf-expired un-fulfilled holds for a given title id
2079 @param authtoken The login session key
2080 @param org The org id of the location in question
2081 @param match_copy A specific copy to limit to
2085 __PACKAGE__->register_method(
2086 method => 'fetch_captured_holds',
2088 'open-ils.circ.captured_holds.expired_on_shelf_or_wrong_shelf.retrieve',
2092 Returns list of shelf-expired un-fulfilled holds OR wrong shelf holds
2093 for a given shelf lib
2097 __PACKAGE__->register_method(
2098 method => 'fetch_captured_holds',
2100 'open-ils.circ.captured_holds.id_list.expired_on_shelf_or_wrong_shelf.retrieve',
2104 Returns list of shelf-expired un-fulfilled holds OR wrong shelf holds
2105 for a given shelf lib
2110 sub fetch_captured_holds {
2111 my( $self, $conn, $auth, $org, $match_copy ) = @_;
2113 my $e = new_editor(authtoken => $auth);
2114 return $e->die_event unless $e->checkauth;
2115 return $e->die_event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
2117 $org ||= $e->requestor->ws_ou;
2119 my $current_copy = { '!=' => undef };
2120 $current_copy = { '=' => $match_copy } if $match_copy;
2123 select => { alhr => ['id'] },
2128 fkey => 'current_copy'
2133 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF, deleted => 'f' },
2135 capture_time => { "!=" => undef },
2136 current_copy => $current_copy,
2137 fulfillment_time => undef,
2138 current_shelf_lib => $org
2142 if($self->api_name =~ /expired/) {
2143 $query->{'where'}->{'+alhr'}->{'-or'} = {
2144 shelf_expire_time => { '<' => 'now'},
2145 cancel_time => { '!=' => undef },
2148 my $hold_ids = $e->json_query( $query );
2150 if ($self->api_name =~ /wrong_shelf/) {
2151 # fetch holds whose current_shelf_lib is $org, but whose pickup
2152 # lib is some other org unit. Ignore already-retrieved holds.
2154 pickup_lib_changed_on_shelf_holds(
2155 $e, $org, [map {$_->{id}} @$hold_ids]);
2156 # match the layout of other items in $hold_ids
2157 push (@$hold_ids, {id => $_}) for @$wrong_shelf;
2161 for my $hold_id (@$hold_ids) {
2162 if($self->api_name =~ /id_list/) {
2163 $conn->respond($hold_id->{id});
2167 $e->retrieve_action_hold_request([
2171 flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
2172 order_by => {anh => 'notify_time desc'}
2182 __PACKAGE__->register_method(
2183 method => "print_expired_holds_stream",
2184 api_name => "open-ils.circ.captured_holds.expired.print.stream",
2188 sub print_expired_holds_stream {
2189 my ($self, $client, $auth, $params) = @_;
2191 # No need to check specific permissions: we're going to call another method
2192 # that will do that.
2193 my $e = new_editor("authtoken" => $auth);
2194 return $e->die_event unless $e->checkauth;
2196 delete($$params{org_id}) unless (int($$params{org_id}));
2197 delete($$params{limit}) unless (int($$params{limit}));
2198 delete($$params{offset}) unless (int($$params{offset}));
2199 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
2200 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
2201 $$params{chunk_size} ||= 10;
2203 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
2205 my @hold_ids = $self->method_lookup(
2206 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
2207 )->run($auth, $params->{"org_id"});
2212 } elsif (defined $U->event_code($hold_ids[0])) {
2214 return $hold_ids[0];
2217 $logger->info("about to stream back up to " . scalar(@hold_ids) . " expired holds");
2220 my @hid_chunk = splice @hold_ids, 0, $params->{"chunk_size"};
2222 my $result_chunk = $e->json_query({
2224 "acp" => ["barcode"],
2226 first_given_name second_given_name family_name alias
2235 "field" => "id", "fkey" => "current_copy",
2238 "field" => "id", "fkey" => "call_number",
2241 "field" => "id", "fkey" => "record"
2245 "acpl" => {"field" => "id", "fkey" => "location"}
2248 "au" => {"field" => "id", "fkey" => "usr"}
2251 "where" => {"+ahr" => {"id" => \@hid_chunk}}
2252 }) or return $e->die_event;
2253 $client->respond($result_chunk);
2260 __PACKAGE__->register_method(
2261 method => "check_title_hold_batch",
2262 api_name => "open-ils.circ.title_hold.is_possible.batch",
2265 desc => '@see open-ils.circ.title_hold.is_possible.batch',
2267 { desc => 'Authentication token', type => 'string'},
2268 { desc => 'Array of Hash of named parameters', type => 'array'},
2271 desc => 'Array of response objects',
2277 sub check_title_hold_batch {
2278 my($self, $client, $authtoken, $param_list, $oargs) = @_;
2279 foreach (@$param_list) {
2280 my ($res) = $self->method_lookup('open-ils.circ.title_hold.is_possible')->run($authtoken, $_, $oargs);
2281 $client->respond($res);
2287 __PACKAGE__->register_method(
2288 method => "check_title_hold",
2289 api_name => "open-ils.circ.title_hold.is_possible",
2291 desc => 'Determines if a hold were to be placed by a given user, ' .
2292 'whether or not said hold would have any potential copies to fulfill it.' .
2293 'The named paramaters of the second argument include: ' .
2294 'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
2295 'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' ,
2297 { desc => 'Authentication token', type => 'string'},
2298 { desc => 'Hash of named parameters', type => 'object'},
2301 desc => 'List of new message IDs (empty if none)',
2307 =head3 check_title_hold (token, hash)
2309 The named fields in the hash are:
2311 patronid - ID of the hold recipient (required)
2312 depth - hold range depth (default 0)
2313 pickup_lib - destination for hold, fallback value for selection_ou
2314 selection_ou - ID of org_unit establishing hard and soft hold boundary settings
2315 issuanceid - ID of the issuance to be held, required for Issuance level hold
2316 partid - ID of the monograph part to be held, required for monograph part level hold
2317 titleid - ID (BRN) of the title to be held, required for Title level hold
2318 volume_id - required for Volume level hold
2319 copy_id - required for Copy level hold
2320 mrid - required for Meta-record level hold
2321 hold_type - T, C (or R or F), I, V or M for Title, Copy, Issuance, Volume or Meta-record (default "T")
2323 All key/value pairs are passed on to do_possibility_checks.
2327 # FIXME: better params checking. what other params are required, if any?
2328 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
2329 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still
2330 # used in conditionals, where it may be undefined, causing a warning.
2331 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
2333 sub check_title_hold {
2334 my( $self, $client, $authtoken, $params ) = @_;
2335 my $e = new_editor(authtoken=>$authtoken);
2336 return $e->event unless $e->checkauth;
2338 my %params = %$params;
2339 my $depth = $params{depth} || 0;
2340 my $selection_ou = $params{selection_ou} || $params{pickup_lib};
2341 my $oargs = $params{oargs} || {};
2343 if($oargs->{events}) {
2344 @{$oargs->{events}} = grep { $e->allowed($_ . '.override', $e->requestor->ws_ou); } @{$oargs->{events}};
2348 my $patron = $e->retrieve_actor_user($params{patronid})
2349 or return $e->event;
2351 if( $e->requestor->id ne $patron->id ) {
2352 return $e->event unless
2353 $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
2356 return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
2358 my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
2359 or return $e->event;
2361 my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
2362 my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
2365 my $return_depth = $hard_boundary; # default depth to return on success
2366 if(defined $soft_boundary and $depth < $soft_boundary) {
2367 # work up the tree and as soon as we find a potential copy, use that depth
2368 # also, make sure we don't go past the hard boundary if it exists
2370 # our min boundary is the greater of user-specified boundary or hard boundary
2371 my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?
2372 $hard_boundary : $depth;
2374 my $depth = $soft_boundary;
2375 while($depth >= $min_depth) {
2376 $logger->info("performing hold possibility check with soft boundary $depth");
2377 @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
2379 $return_depth = $depth;
2384 } elsif(defined $hard_boundary and $depth < $hard_boundary) {
2385 # there is no soft boundary, enforce the hard boundary if it exists
2386 $logger->info("performing hold possibility check with hard boundary $hard_boundary");
2387 @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
2389 # no boundaries defined, fall back to user specifed boundary or no boundary
2390 $logger->info("performing hold possibility check with no boundary");
2391 @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
2394 my $place_unfillable = 0;
2395 $place_unfillable = 1 if $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
2400 "depth" => $return_depth,
2401 "local_avail" => $status[1]
2403 } elsif ($status[2]) {
2404 my $n = scalar @{$status[2]};
2405 return {"success" => 0, "last_event" => $status[2]->[$n - 1], "age_protected_copy" => $status[3], "place_unfillable" => $place_unfillable};
2407 return {"success" => 0, "age_protected_copy" => $status[3], "place_unfillable" => $place_unfillable};
2413 sub do_possibility_checks {
2414 my($e, $patron, $request_lib, $depth, %params) = @_;
2416 my $issuanceid = $params{issuanceid} || "";
2417 my $partid = $params{partid} || "";
2418 my $titleid = $params{titleid} || "";
2419 my $volid = $params{volume_id};
2420 my $copyid = $params{copy_id};
2421 my $mrid = $params{mrid} || "";
2422 my $pickup_lib = $params{pickup_lib};
2423 my $hold_type = $params{hold_type} || 'T';
2424 my $selection_ou = $params{selection_ou} || $pickup_lib;
2425 my $holdable_formats = $params{holdable_formats};
2426 my $oargs = $params{oargs} || {};
2433 if( $hold_type eq OILS_HOLD_TYPE_FORCE || $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_COPY ) {
2435 return $e->event unless $copy = $e->retrieve_asset_copy($copyid);
2436 return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
2437 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2439 return (1, 1, []) if( $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_FORCE);
2440 return verify_copy_for_hold(
2441 $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib, $oargs
2444 } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2446 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
2447 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2449 return _check_volume_hold_is_possible(
2450 $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2453 } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
2455 return _check_title_hold_is_possible(
2456 $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, undef, $oargs
2459 } elsif( $hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2461 return _check_issuance_hold_is_possible(
2462 $issuanceid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2465 } elsif( $hold_type eq OILS_HOLD_TYPE_MONOPART ) {
2467 return _check_monopart_hold_is_possible(
2468 $partid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2471 } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2473 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
2474 my @recs = map { $_->source } @$maps;
2476 for my $rec (@recs) {
2477 @status = _check_title_hold_is_possible(
2478 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $holdable_formats, $oargs
2484 # else { Unrecognized hold_type ! } # FIXME: return error? or 0?
2488 sub create_ranged_org_filter {
2489 my($e, $selection_ou, $depth) = @_;
2491 # find the orgs from which this hold may be fulfilled,
2492 # based on the selection_ou and depth
2494 my $top_org = $e->search_actor_org_unit([
2495 {parent_ou => undef},
2496 {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
2499 return () if $depth == $top_org->ou_type->depth;
2501 my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
2502 %org_filter = (circ_lib => []);
2503 push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
2505 $logger->info("hold org filter at depth $depth and selection_ou ".
2506 "$selection_ou created list of @{$org_filter{circ_lib}}");
2512 sub _check_title_hold_is_possible {
2513 my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $holdable_formats, $oargs ) = @_;
2515 my ($types, $formats, $lang);
2516 if (defined($holdable_formats)) {
2517 ($types, $formats, $lang) = split '-', $holdable_formats;
2520 my $e = new_editor();
2521 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2523 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2524 my $copies = $e->json_query(
2526 select => { acp => ['id', 'circ_lib'] },
2531 fkey => 'call_number',
2535 filter => { id => $titleid },
2543 ( $types ? (item_type => [split '', $types]) : () ),
2544 ( $formats ? (item_form => [split '', $formats]) : () ),
2545 ( $lang ? (item_lang => $lang) : () )
2550 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2551 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' },
2552 acpm => { field => 'target_copy', type => 'left' } # ignore part-linked copies
2556 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter },
2557 '+acpm' => { target_copy => undef } # ignore part-linked copies
2562 $logger->info("title possible found ".scalar(@$copies)." potential copies");
2566 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2567 "payload" => {"fail_part" => "no_ultimate_items"}
2572 # -----------------------------------------------------------------------
2573 # sort the copies into buckets based on their circ_lib proximity to
2574 # the patron's home_ou.
2575 # -----------------------------------------------------------------------
2577 my $home_org = $patron->home_ou;
2578 my $req_org = $request_lib->id;
2580 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2582 $prox_cache{$home_org} =
2583 $e->search_actor_org_unit_proximity({from_org => $home_org})
2584 unless $prox_cache{$home_org};
2585 my $home_prox = $prox_cache{$home_org};
2588 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2589 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2591 my @keys = sort { $a <=> $b } keys %buckets;
2594 if( $home_org ne $req_org ) {
2595 # -----------------------------------------------------------------------
2596 # shove the copies close to the request_lib into the primary buckets
2597 # directly before the farthest away copies. That way, they are not
2598 # given priority, but they are checked before the farthest copies.
2599 # -----------------------------------------------------------------------
2600 $prox_cache{$req_org} =
2601 $e->search_actor_org_unit_proximity({from_org => $req_org})
2602 unless $prox_cache{$req_org};
2603 my $req_prox = $prox_cache{$req_org};
2606 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2607 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2609 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2610 my $new_key = $highest_key - 0.5; # right before the farthest prox
2611 my @keys2 = sort { $a <=> $b } keys %buckets2;
2612 for my $key (@keys2) {
2613 last if $key >= $highest_key;
2614 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2618 @keys = sort { $a <=> $b } keys %buckets;
2623 my $age_protect_only = 0;
2624 OUTER: for my $key (@keys) {
2625 my @cps = @{$buckets{$key}};
2627 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2629 for my $copyid (@cps) {
2631 next if $seen{$copyid};
2632 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2633 my $copy = $e->retrieve_asset_copy($copyid);
2634 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2636 unless($title) { # grab the title if we don't already have it
2637 my $vol = $e->retrieve_asset_call_number(
2638 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2639 $title = $vol->record;
2642 @status = verify_copy_for_hold(
2643 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2645 $age_protect_only ||= $status[3];
2646 last OUTER if $status[0];
2650 $status[3] = $age_protect_only;
2654 sub _check_issuance_hold_is_possible {
2655 my( $issuanceid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2657 my $e = new_editor();
2658 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2660 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2661 my $copies = $e->json_query(
2663 select => { acp => ['id', 'circ_lib'] },
2669 filter => { issuance => $issuanceid }
2671 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2672 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2676 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2682 $logger->info("issuance possible found ".scalar(@$copies)." potential copies");
2686 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2687 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2692 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2693 "payload" => {"fail_part" => "no_ultimate_items"}
2701 # -----------------------------------------------------------------------
2702 # sort the copies into buckets based on their circ_lib proximity to
2703 # the patron's home_ou.
2704 # -----------------------------------------------------------------------
2706 my $home_org = $patron->home_ou;
2707 my $req_org = $request_lib->id;
2709 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2711 $prox_cache{$home_org} =
2712 $e->search_actor_org_unit_proximity({from_org => $home_org})
2713 unless $prox_cache{$home_org};
2714 my $home_prox = $prox_cache{$home_org};
2717 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2718 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2720 my @keys = sort { $a <=> $b } keys %buckets;
2723 if( $home_org ne $req_org ) {
2724 # -----------------------------------------------------------------------
2725 # shove the copies close to the request_lib into the primary buckets
2726 # directly before the farthest away copies. That way, they are not
2727 # given priority, but they are checked before the farthest copies.
2728 # -----------------------------------------------------------------------
2729 $prox_cache{$req_org} =
2730 $e->search_actor_org_unit_proximity({from_org => $req_org})
2731 unless $prox_cache{$req_org};
2732 my $req_prox = $prox_cache{$req_org};
2735 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2736 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2738 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2739 my $new_key = $highest_key - 0.5; # right before the farthest prox
2740 my @keys2 = sort { $a <=> $b } keys %buckets2;
2741 for my $key (@keys2) {
2742 last if $key >= $highest_key;
2743 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2747 @keys = sort { $a <=> $b } keys %buckets;
2752 my $age_protect_only = 0;
2753 OUTER: for my $key (@keys) {
2754 my @cps = @{$buckets{$key}};
2756 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2758 for my $copyid (@cps) {
2760 next if $seen{$copyid};
2761 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2762 my $copy = $e->retrieve_asset_copy($copyid);
2763 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2765 unless($title) { # grab the title if we don't already have it
2766 my $vol = $e->retrieve_asset_call_number(
2767 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2768 $title = $vol->record;
2771 @status = verify_copy_for_hold(
2772 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2774 $age_protect_only ||= $status[3];
2775 last OUTER if $status[0];
2780 if (!defined($empty_ok)) {
2781 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2782 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2785 return (1,0) if ($empty_ok);
2787 $status[3] = $age_protect_only;
2791 sub _check_monopart_hold_is_possible {
2792 my( $partid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2794 my $e = new_editor();
2795 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2797 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2798 my $copies = $e->json_query(
2800 select => { acp => ['id', 'circ_lib'] },
2804 field => 'target_copy',
2806 filter => { part => $partid }
2808 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2809 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2813 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2819 $logger->info("monopart possible found ".scalar(@$copies)." potential copies");
2823 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2824 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2829 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2830 "payload" => {"fail_part" => "no_ultimate_items"}
2838 # -----------------------------------------------------------------------
2839 # sort the copies into buckets based on their circ_lib proximity to
2840 # the patron's home_ou.
2841 # -----------------------------------------------------------------------
2843 my $home_org = $patron->home_ou;
2844 my $req_org = $request_lib->id;
2846 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2848 $prox_cache{$home_org} =
2849 $e->search_actor_org_unit_proximity({from_org => $home_org})
2850 unless $prox_cache{$home_org};
2851 my $home_prox = $prox_cache{$home_org};
2854 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2855 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2857 my @keys = sort { $a <=> $b } keys %buckets;
2860 if( $home_org ne $req_org ) {
2861 # -----------------------------------------------------------------------
2862 # shove the copies close to the request_lib into the primary buckets
2863 # directly before the farthest away copies. That way, they are not
2864 # given priority, but they are checked before the farthest copies.
2865 # -----------------------------------------------------------------------
2866 $prox_cache{$req_org} =
2867 $e->search_actor_org_unit_proximity({from_org => $req_org})
2868 unless $prox_cache{$req_org};
2869 my $req_prox = $prox_cache{$req_org};
2872 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2873 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2875 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2876 my $new_key = $highest_key - 0.5; # right before the farthest prox
2877 my @keys2 = sort { $a <=> $b } keys %buckets2;
2878 for my $key (@keys2) {
2879 last if $key >= $highest_key;
2880 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2884 @keys = sort { $a <=> $b } keys %buckets;
2889 my $age_protect_only = 0;
2890 OUTER: for my $key (@keys) {
2891 my @cps = @{$buckets{$key}};
2893 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2895 for my $copyid (@cps) {
2897 next if $seen{$copyid};
2898 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2899 my $copy = $e->retrieve_asset_copy($copyid);
2900 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2902 unless($title) { # grab the title if we don't already have it
2903 my $vol = $e->retrieve_asset_call_number(
2904 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2905 $title = $vol->record;
2908 @status = verify_copy_for_hold(
2909 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2911 $age_protect_only ||= $status[3];
2912 last OUTER if $status[0];
2917 if (!defined($empty_ok)) {
2918 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2919 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2922 return (1,0) if ($empty_ok);
2924 $status[3] = $age_protect_only;
2929 sub _check_volume_hold_is_possible {
2930 my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2931 my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
2932 my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
2933 $logger->info("checking possibility of volume hold for volume ".$vol->id);
2935 my $filter_copies = [];
2936 for my $copy (@$copies) {
2937 # ignore part-mapped copies for regular volume level holds
2938 push(@$filter_copies, $copy) unless
2939 new_editor->search_asset_copy_part_map({target_copy => $copy->id})->[0];
2941 $copies = $filter_copies;
2946 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2947 "payload" => {"fail_part" => "no_ultimate_items"}
2953 my $age_protect_only = 0;
2954 for my $copy ( @$copies ) {
2955 @status = verify_copy_for_hold(
2956 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs );
2957 $age_protect_only ||= $status[3];
2960 $status[3] = $age_protect_only;
2966 sub verify_copy_for_hold {
2967 my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs ) = @_;
2968 # $oargs should be undef unless we're overriding.
2969 $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
2970 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2973 requestor => $requestor,
2976 title_descriptor => $title->fixed_fields,
2977 pickup_lib => $pickup_lib,
2978 request_lib => $request_lib,
2980 show_event_list => 1
2984 # Check for override permissions on events.
2985 if ($oargs && $permitted && scalar @$permitted) {
2986 # Remove the events from permitted that we can override.
2987 if ($oargs->{events}) {
2988 foreach my $evt (@{$oargs->{events}}) {
2989 $permitted = [grep {$_->{textcode} ne $evt} @{$permitted}];
2992 # Now, we handle the override all case by checking remaining
2993 # events against override permissions.
2994 if (scalar @$permitted && $oargs->{all}) {
2995 # Pre-set events and failed members of oargs to empty
2996 # arrays, if they are not set, yet.
2997 $oargs->{events} = [] unless ($oargs->{events});
2998 $oargs->{failed} = [] unless ($oargs->{failed});
2999 # When we're done with these checks, we swap permitted
3000 # with a reference to @disallowed.
3001 my @disallowed = ();
3002 foreach my $evt (@{$permitted}) {
3003 # Check if we've already seen the event in this
3004 # session and it failed.
3005 if (grep {$_ eq $evt->{textcode}} @{$oargs->{failed}}) {
3006 push(@disallowed, $evt);
3008 # We have to check if the requestor has the
3009 # override permission.
3011 # AppUtils::check_user_perms returns the perm if
3012 # the user doesn't have it, undef if they do.
3013 if ($apputils->check_user_perms($requestor->id, $requestor->ws_ou, $evt->{textcode} . '.override')) {
3014 push(@disallowed, $evt);
3015 push(@{$oargs->{failed}}, $evt->{textcode});
3017 push(@{$oargs->{events}}, $evt->{textcode});
3021 $permitted = \@disallowed;
3025 my $age_protect_only = 0;
3026 if (@$permitted == 1 && @$permitted[0]->{textcode} eq 'ITEM_AGE_PROTECTED') {
3027 $age_protect_only = 1;
3031 (not scalar @$permitted), # true if permitted is an empty arrayref
3032 ( # XXX This test is of very dubious value; someone should figure
3033 # out what if anything is checking this value
3034 ($copy->circ_lib == $pickup_lib) and
3035 ($copy->status == OILS_COPY_STATUS_AVAILABLE)
3044 sub find_nearest_permitted_hold {
3047 my $editor = shift; # CStoreEditor object
3048 my $copy = shift; # copy to target
3049 my $user = shift; # staff
3050 my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
3052 my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
3054 my $bc = $copy->barcode;
3056 # find any existing holds that already target this copy
3057 my $old_holds = $editor->search_action_hold_request(
3058 { current_copy => $copy->id,
3059 cancel_time => undef,
3060 capture_time => undef
3064 my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
3066 $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
3067 " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
3069 my $fifo = $U->ou_ancestor_setting_value($user->ws_ou, 'circ.holds_fifo');
3071 # the nearest_hold API call now needs this
3072 $copy->call_number($editor->retrieve_asset_call_number($copy->call_number))
3073 unless ref $copy->call_number;
3075 # search for what should be the best holds for this copy to fulfill
3076 my $best_holds = $U->storagereq(
3077 "open-ils.storage.action.hold_request.nearest_hold.atomic",
3078 $user->ws_ou, $copy, 100, $hold_stall_interval, $fifo );
3080 # Add any pre-targeted holds to the list too? Unless they are already there, anyway.
3082 for my $holdid (@$old_holds) {
3083 next unless $holdid;
3084 push(@$best_holds, $holdid) unless ( grep { ''.$holdid eq ''.$_ } @$best_holds );
3088 unless(@$best_holds) {
3089 $logger->info("circulator: no suitable holds found for copy $bc");
3090 return (undef, $evt);
3096 # for each potential hold, we have to run the permit script
3097 # to make sure the hold is actually permitted.
3100 for my $holdid (@$best_holds) {
3101 next unless $holdid;
3102 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
3104 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
3105 # Force and recall holds bypass all rules
3106 if ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
3110 my $reqr = $reqr_cache{$hold->requestor} || $editor->retrieve_actor_user($hold->requestor);
3111 my $rlib = $org_cache{$hold->request_lib} || $editor->retrieve_actor_org_unit($hold->request_lib);
3113 $reqr_cache{$hold->requestor} = $reqr;
3114 $org_cache{$hold->request_lib} = $rlib;
3116 # see if this hold is permitted
3117 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
3119 patron_id => $hold->usr,
3122 pickup_lib => $hold->pickup_lib,
3123 request_lib => $rlib,
3135 unless( $best_hold ) { # no "good" permitted holds were found
3137 $logger->info("circulator: no suitable holds found for copy $bc");
3138 return (undef, $evt);
3141 $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
3143 # indicate a permitted hold was found
3144 return $best_hold if $check_only;
3146 # we've found a permitted hold. we need to "grab" the copy
3147 # to prevent re-targeted holds (next part) from re-grabbing the copy
3148 $best_hold->current_copy($copy->id);
3149 $editor->update_action_hold_request($best_hold)
3150 or return (undef, $editor->event);
3155 # re-target any other holds that already target this copy
3156 for my $old_hold (@$old_holds) {
3157 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
3158 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
3159 $old_hold->id." after a better hold [".$best_hold->id."] was found");
3160 $old_hold->clear_current_copy;
3161 $old_hold->clear_prev_check_time;
3162 $editor->update_action_hold_request($old_hold)
3163 or return (undef, $editor->event);
3164 push(@retarget, $old_hold->id);
3167 return ($best_hold, undef, (@retarget) ? \@retarget : undef);
3175 __PACKAGE__->register_method(
3176 method => 'all_rec_holds',
3177 api_name => 'open-ils.circ.holds.retrieve_all_from_title',
3181 my( $self, $conn, $auth, $title_id, $args ) = @_;
3183 my $e = new_editor(authtoken=>$auth);
3184 $e->checkauth or return $e->event;
3185 $e->allowed('VIEW_HOLD') or return $e->event;
3188 $args->{fulfillment_time} = undef; # we don't want to see old fulfilled holds
3189 $args->{cancel_time} = undef;
3192 metarecord_holds => []
3194 , volume_holds => []
3196 , recall_holds => []
3199 , issuance_holds => []
3202 my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
3204 $resp->{metarecord_holds} = $e->search_action_hold_request(
3205 { hold_type => OILS_HOLD_TYPE_METARECORD,
3206 target => $mr_map->metarecord,
3212 $resp->{title_holds} = $e->search_action_hold_request(
3214 hold_type => OILS_HOLD_TYPE_TITLE,
3215 target => $title_id,
3219 my $parts = $e->search_biblio_monograph_part(
3225 $resp->{part_holds} = $e->search_action_hold_request(
3227 hold_type => OILS_HOLD_TYPE_MONOPART,
3233 my $subs = $e->search_serial_subscription(
3234 { record_entry => $title_id }, {idlist=>1});
3237 my $issuances = $e->search_serial_issuance(
3238 {subscription => $subs}, {idlist=>1}
3242 $resp->{issuance_holds} = $e->search_action_hold_request(
3244 hold_type => OILS_HOLD_TYPE_ISSUANCE,
3245 target => $issuances,
3252 my $vols = $e->search_asset_call_number(
3253 { record => $title_id, deleted => 'f' }, {idlist=>1});
3255 return $resp unless @$vols;
3257 $resp->{volume_holds} = $e->search_action_hold_request(
3259 hold_type => OILS_HOLD_TYPE_VOLUME,
3264 my $copies = $e->search_asset_copy(
3265 { call_number => $vols, deleted => 'f' }, {idlist=>1});
3267 return $resp unless @$copies;
3269 $resp->{copy_holds} = $e->search_action_hold_request(
3271 hold_type => OILS_HOLD_TYPE_COPY,
3276 $resp->{recall_holds} = $e->search_action_hold_request(
3278 hold_type => OILS_HOLD_TYPE_RECALL,
3283 $resp->{force_holds} = $e->search_action_hold_request(
3285 hold_type => OILS_HOLD_TYPE_FORCE,
3297 __PACKAGE__->register_method(
3298 method => 'uber_hold',
3300 api_name => 'open-ils.circ.hold.details.retrieve'
3304 my($self, $client, $auth, $hold_id, $args) = @_;
3305 my $e = new_editor(authtoken=>$auth);
3306 $e->checkauth or return $e->event;
3307 return uber_hold_impl($e, $hold_id, $args);
3310 __PACKAGE__->register_method(
3311 method => 'batch_uber_hold',
3314 api_name => 'open-ils.circ.hold.details.batch.retrieve'
3317 sub batch_uber_hold {
3318 my($self, $client, $auth, $hold_ids, $args) = @_;
3319 my $e = new_editor(authtoken=>$auth);
3320 $e->checkauth or return $e->event;
3321 $client->respond(uber_hold_impl($e, $_, $args)) for @$hold_ids;
3325 sub uber_hold_impl {
3326 my($e, $hold_id, $args) = @_;
3329 my $hold = $e->retrieve_action_hold_request(
3334 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
3337 ) or return $e->event;
3339 if($hold->usr->id ne $e->requestor->id) {
3340 # caller is asking for someone else's hold
3341 $e->allowed('VIEW_HOLD') or return $e->event;
3342 $hold->notes( # filter out any non-staff ("private") notes (unless marked as public)
3343 [ grep { $U->is_true($_->staff) or $U->is_true($_->pub) } @{$hold->notes} ] );
3346 # caller is asking for own hold, but may not have permission to view staff notes
3347 unless($e->allowed('VIEW_HOLD')) {
3348 $hold->notes( # filter out any staff notes (unless marked as public)
3349 [ grep { !$U->is_true($_->staff) or $U->is_true($_->pub) } @{$hold->notes} ] );
3353 my $user = $hold->usr;
3354 $hold->usr($user->id);
3357 my( $mvr, $volume, $copy, $issuance, $part, $bre ) = find_hold_mvr($e, $hold, $args->{suppress_mvr});
3359 flesh_hold_notices([$hold], $e) unless $args->{suppress_notices};
3360 flesh_hold_transits([$hold]) unless $args->{suppress_transits};
3362 my $details = retrieve_hold_queue_status_impl($e, $hold);
3367 ($copy ? (copy => $copy) : ()),
3368 ($volume ? (volume => $volume) : ()),
3369 ($issuance ? (issuance => $issuance) : ()),
3370 ($part ? (part => $part) : ()),
3371 ($args->{include_bre} ? (bre => $bre) : ()),
3372 ($args->{suppress_mvr} ? () : (mvr => $mvr)),
3376 unless($args->{suppress_patron_details}) {
3377 my $card = $e->retrieve_actor_card($user->card) or return $e->event;
3378 $resp->{patron_first} = $user->first_given_name,
3379 $resp->{patron_last} = $user->family_name,
3380 $resp->{patron_barcode} = $card->barcode,
3381 $resp->{patron_alias} = $user->alias,
3389 # -----------------------------------------------------
3390 # Returns the MVR object that represents what the
3392 # -----------------------------------------------------
3394 my( $e, $hold, $no_mvr ) = @_;
3402 if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
3403 my $mr = $e->retrieve_metabib_metarecord($hold->target)
3404 or return $e->event;
3405 $tid = $mr->master_record;
3407 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
3408 $tid = $hold->target;
3410 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
3411 $volume = $e->retrieve_asset_call_number($hold->target)
3412 or return $e->event;
3413 $tid = $volume->record;
3415 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
3416 $issuance = $e->retrieve_serial_issuance([
3418 {flesh => 1, flesh_fields => {siss => [ qw/subscription/ ]}}
3419 ]) or return $e->event;
3421 $tid = $issuance->subscription->record_entry;
3423 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_MONOPART ) {
3424 $part = $e->retrieve_biblio_monograph_part([
3426 ]) or return $e->event;
3428 $tid = $part->record;
3430 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_COPY || $hold->hold_type eq OILS_HOLD_TYPE_RECALL || $hold->hold_type eq OILS_HOLD_TYPE_FORCE ) {
3431 $copy = $e->retrieve_asset_copy([
3433 {flesh => 1, flesh_fields => {acp => ['call_number']}}
3434 ]) or return $e->event;
3436 $volume = $copy->call_number;
3437 $tid = $volume->record;
3440 if(!$copy and ref $hold->current_copy ) {
3441 $copy = $hold->current_copy;
3442 $hold->current_copy($copy->id);
3445 if(!$volume and $copy) {
3446 $volume = $e->retrieve_asset_call_number($copy->call_number);
3449 # TODO return metarcord mvr for M holds
3450 my $title = $e->retrieve_biblio_record_entry($tid);
3451 return ( ($no_mvr) ? undef : $U->record_to_mvr($title), $volume, $copy, $issuance, $part, $title );
3454 __PACKAGE__->register_method(
3455 method => 'clear_shelf_cache',
3456 api_name => 'open-ils.circ.hold.clear_shelf.get_cache',
3460 Returns the holds processed with the given cache key
3465 sub clear_shelf_cache {
3466 my($self, $client, $auth, $cache_key, $chunk_size) = @_;
3467 my $e = new_editor(authtoken => $auth, xact => 1);
3468 return $e->die_event unless $e->checkauth and $e->allowed('VIEW_HOLD');
3471 my $hold_data = OpenSRF::Utils::Cache->new('global')->get_cache($cache_key);
3474 $logger->info("no hold data found in cache"); # XXX TODO return event
3480 foreach (keys %$hold_data) {
3481 $maximum += scalar(@{ $hold_data->{$_} });
3483 $client->respond({"maximum" => $maximum, "progress" => 0});
3485 for my $action (sort keys %$hold_data) {
3486 while (@{$hold_data->{$action}}) {
3487 my @hid_chunk = splice @{$hold_data->{$action}}, 0, $chunk_size;
3489 my $result_chunk = $e->json_query({
3491 "acp" => ["barcode"],
3493 first_given_name second_given_name family_name alias
3496 "acnp" => [{column => "label", alias => "prefix"}],
3497 "acns" => [{column => "label", alias => "suffix"}],
3505 "field" => "id", "fkey" => "current_copy",
3508 "field" => "id", "fkey" => "call_number",
3511 "field" => "id", "fkey" => "record"
3514 "field" => "id", "fkey" => "prefix"
3517 "field" => "id", "fkey" => "suffix"
3521 "acpl" => {"field" => "id", "fkey" => "location"}
3524 "au" => {"field" => "id", "fkey" => "usr"}
3527 "where" => {"+ahr" => {"id" => \@hid_chunk}}
3528 }, {"substream" => 1}) or return $e->die_event;
3532 +{"action" => $action, "hold_details" => $_}
3543 __PACKAGE__->register_method(
3544 method => 'clear_shelf_process',
3546 api_name => 'open-ils.circ.hold.clear_shelf.process',
3549 1. Find all holds that have expired on the holds shelf
3551 3. If a clear-shelf status is configured, put targeted copies into this status
3552 4. Divide copies into 3 groups: items to transit, items to reshelve, and items
3553 that are needed for holds. No subsequent action is taken on the holds
3554 or items after grouping.
3559 sub clear_shelf_process {
3560 my($self, $client, $auth, $org_id, $match_copy) = @_;
3562 my $e = new_editor(authtoken=>$auth);
3563 $e->checkauth or return $e->die_event;
3564 my $cache = OpenSRF::Utils::Cache->new('global');
3566 $org_id ||= $e->requestor->ws_ou;
3567 $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
3569 my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
3571 my @hold_ids = $self->method_lookup(
3572 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
3573 )->run($auth, $org_id, $match_copy);
3578 my @canceled_holds; # newly canceled holds
3579 my $chunk_size = 25; # chunked status updates
3581 for my $hold_id (@hold_ids) {
3583 $logger->info("Clear shelf processing hold $hold_id");
3585 my $hold = $e->retrieve_action_hold_request([
3588 flesh_fields => {ahr => ['current_copy']}
3592 if (!$hold->cancel_time) { # may be canceled but still on the holds shelf
3593 $hold->cancel_time('now');
3594 $hold->cancel_cause(2); # Hold Shelf expiration
3595 $e->update_action_hold_request($hold) or return $e->die_event;
3596 delete_hold_copy_maps($self, $e, $hold->id) and return $e->die_event;
3597 push(@canceled_holds, $hold_id);
3600 my $copy = $hold->current_copy;
3602 if($copy_status or $copy_status == 0) {
3603 # if a clear-shelf copy status is defined, update the copy
3604 $copy->status($copy_status);
3605 $copy->edit_date('now');
3606 $copy->editor($e->requestor->id);
3607 $e->update_asset_copy($copy) or return $e->die_event;
3610 push(@holds, $hold);
3611 $client->respond({maximum => scalar(@holds), progress => $counter}) if ( (++$counter % $chunk_size) == 0);
3620 pl_changed => pickup_lib_changed_on_shelf_holds($e, $org_id, \@hold_ids)
3623 for my $hold (@holds) {
3625 my $copy = $hold->current_copy;
3626 my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
3628 if($alt_hold and !$match_copy) {
3630 push(@{$cache_data{hold}}, $hold->id); # copy is needed for a hold
3632 } elsif($copy->circ_lib != $e->requestor->ws_ou) {
3634 push(@{$cache_data{transit}}, $hold->id); # copy needs to transit
3638 push(@{$cache_data{shelf}}, $hold->id); # copy needs to go back to the shelf
3642 my $cache_key = md5_hex(time . $$ . rand());
3643 $logger->info("clear_shelf_cache: storing under $cache_key");
3644 $cache->put_cache($cache_key, \%cache_data, 7200); # TODO: 2 hours. configurable?
3646 # tell the client we're done
3647 $client->respond_complete({cache_key => $cache_key});
3650 # fire off the hold cancelation trigger and wait for response so don't flood the service
3652 # refetch the holds to pick up the caclulated cancel_time,
3653 # which may be needed by Action/Trigger
3655 my $updated_holds = [];
3656 $updated_holds = $e->search_action_hold_request({id => \@canceled_holds}, {substream => 1}) if (@canceled_holds > 0);
3659 $U->create_events_for_hook(
3660 'hold_request.cancel.expire_holds_shelf',
3661 $_, $org_id, undef, undef, 1) for @$updated_holds;
3664 # tell the client we're done
3665 $client->respond_complete;
3669 # returns IDs for holds that are on the holds shelf but
3670 # have had their pickup_libs change while on the shelf.
3671 sub pickup_lib_changed_on_shelf_holds {
3674 my $ignore_holds = shift;
3675 $ignore_holds = [$ignore_holds] if !ref($ignore_holds);
3678 select => { alhr => ['id'] },
3683 fkey => 'current_copy'
3688 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
3690 capture_time => { "!=" => undef },
3691 fulfillment_time => undef,
3692 current_shelf_lib => $org_id,
3693 pickup_lib => {'!=' => {'+alhr' => 'current_shelf_lib'}}
3698 $query->{where}->{'+alhr'}->{id} =
3699 {'not in' => $ignore_holds} if @$ignore_holds;
3701 my $hold_ids = $e->json_query($query);
3702 return [ map { $_->{id} } @$hold_ids ];
3705 __PACKAGE__->register_method(
3706 method => 'usr_hold_summary',
3707 api_name => 'open-ils.circ.holds.user_summary',
3709 Returns a summary of holds statuses for a given user
3713 sub usr_hold_summary {
3714 my($self, $conn, $auth, $user_id) = @_;
3716 my $e = new_editor(authtoken=>$auth);
3717 $e->checkauth or return $e->event;
3718 $e->allowed('VIEW_HOLD') or return $e->event;
3720 my $holds = $e->search_action_hold_request(
3723 fulfillment_time => undef,
3724 cancel_time => undef,
3728 my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
3729 $summary{_hold_status($e, $_)} += 1 for @$holds;
3735 __PACKAGE__->register_method(
3736 method => 'hold_has_copy_at',
3737 api_name => 'open-ils.circ.hold.has_copy_at',
3740 'Returns the ID of the found copy and name of the shelving location if there is ' .
3741 'an available copy at the specified org unit. Returns empty hash otherwise. ' .
3742 'The anticipated use for this method is to determine whether an item is ' .
3743 'available at the library where the user is placing the hold (or, alternatively, '.
3744 'at the pickup library) to encourage bypassing the hold placement and just ' .
3745 'checking out the item.' ,
3747 { desc => 'Authentication Token', type => 'string' },
3748 { desc => 'Method Arguments. Options include: hold_type, hold_target, org_unit. '
3749 . 'hold_type is the hold type code (T, V, C, M, ...). '
3750 . 'hold_target is the identifier of the hold target object. '
3751 . 'org_unit is org unit ID.',
3756 desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
3762 sub hold_has_copy_at {
3763 my($self, $conn, $auth, $args) = @_;
3765 my $e = new_editor(authtoken=>$auth);
3766 $e->checkauth or return $e->event;
3768 my $hold_type = $$args{hold_type};
3769 my $hold_target = $$args{hold_target};
3770 my $org_unit = $$args{org_unit};
3773 select => {acp => ['id'], acpl => ['name']},
3776 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
3777 ccs => {field => 'id', filter => { holdable => 't'}, fkey => 'status' }
3780 where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit, status => [0,7]}},
3784 if($hold_type eq 'C' or $hold_type eq 'F' or $hold_type eq 'R') {
3786 $query->{where}->{'+acp'}->{id} = $hold_target;
3788 } elsif($hold_type eq 'V') {
3790 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3792 } elsif($hold_type eq 'P') {
3794 $query->{from}->{acp}->{acpm} = {
3795 field => 'target_copy',
3797 filter => {part => $hold_target},
3800 } elsif($hold_type eq 'I') {
3802 $query->{from}->{acp}->{sitem} = {
3805 filter => {issuance => $hold_target},
3808 } elsif($hold_type eq 'T') {
3810 $query->{from}->{acp}->{acn} = {
3812 fkey => 'call_number',
3816 filter => {id => $hold_target},
3824 $query->{from}->{acp}->{acn} = {
3826 fkey => 'call_number',
3835 filter => {metarecord => $hold_target},
3843 my $res = $e->json_query($query)->[0] or return {};
3844 return {copy => $res->{id}, location => $res->{name}} if $res;
3848 # returns true if the user already has an item checked out
3849 # that could be used to fulfill the requested hold.
3850 sub hold_item_is_checked_out {
3851 my($e, $user_id, $hold_type, $hold_target) = @_;
3854 select => {acp => ['id']},
3855 from => {acp => {}},
3859 in => { # copies for circs the user has checked out
3860 select => {circ => ['target_copy']},
3864 checkin_time => undef,
3866 {stop_fines => ["MAXFINES","LONGOVERDUE"]},
3867 {stop_fines => undef}
3877 if($hold_type eq 'C' || $hold_type eq 'R' || $hold_type eq 'F') {
3879 $query->{where}->{'+acp'}->{id}->{in}->{where}->{'target_copy'} = $hold_target;
3881 } elsif($hold_type eq 'V') {
3883 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3885 } elsif($hold_type eq 'P') {
3887 $query->{from}->{acp}->{acpm} = {
3888 field => 'target_copy',
3890 filter => {part => $hold_target},
3893 } elsif($hold_type eq 'I') {
3895 $query->{from}->{acp}->{sitem} = {
3898 filter => {issuance => $hold_target},
3901 } elsif($hold_type eq 'T') {
3903 $query->{from}->{acp}->{acn} = {
3905 fkey => 'call_number',
3909 filter => {id => $hold_target},
3917 $query->{from}->{acp}->{acn} = {
3919 fkey => 'call_number',
3928 filter => {metarecord => $hold_target},
3936 return $e->json_query($query)->[0];
3939 __PACKAGE__->register_method(
3940 method => 'change_hold_title',
3941 api_name => 'open-ils.circ.hold.change_title',
3944 Updates all title level holds targeting the specified bibs to point a new bib./,
3946 { desc => 'Authentication Token', type => 'string' },
3947 { desc => 'New Target Bib Id', type => 'number' },
3948 { desc => 'Old Target Bib Ids', type => 'array' },
3950 return => { desc => '1 on success' }
3954 __PACKAGE__->register_method(
3955 method => 'change_hold_title_for_specific_holds',
3956 api_name => 'open-ils.circ.hold.change_title.specific_holds',
3959 Updates specified holds to target new bib./,
3961 { desc => 'Authentication Token', type => 'string' },
3962 { desc => 'New Target Bib Id', type => 'number' },
3963 { desc => 'Holds Ids for holds to update', type => 'array' },
3965 return => { desc => '1 on success' }
3970 sub change_hold_title {
3971 my( $self, $client, $auth, $new_bib_id, $bib_ids ) = @_;
3973 my $e = new_editor(authtoken=>$auth, xact=>1);
3974 return $e->die_event unless $e->checkauth;
3976 my $holds = $e->search_action_hold_request(
3979 cancel_time => undef,
3980 fulfillment_time => undef,
3986 flesh_fields => { ahr => ['usr'] }
3992 for my $hold (@$holds) {
3993 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3994 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3995 $hold->target( $new_bib_id );
3996 $e->update_action_hold_request($hold) or return $e->die_event;
4001 _reset_hold($self, $e->requestor, $_) for @$holds;
4006 sub change_hold_title_for_specific_holds {
4007 my( $self, $client, $auth, $new_bib_id, $hold_ids ) = @_;
4009 my $e = new_editor(authtoken=>$auth, xact=>1);
4010 return $e->die_event unless $e->checkauth;
4012 my $holds = $e->search_action_hold_request(
4015 cancel_time => undef,
4016 fulfillment_time => undef,
4022 flesh_fields => { ahr => ['usr'] }
4028 for my $hold (@$holds) {
4029 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
4030 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
4031 $hold->target( $new_bib_id );
4032 $e->update_action_hold_request($hold) or return $e->die_event;
4037 _reset_hold($self, $e->requestor, $_) for @$holds;
4042 __PACKAGE__->register_method(
4043 method => 'rec_hold_count',
4044 api_name => 'open-ils.circ.bre.holds.count',
4046 desc => q/Returns the total number of holds that target the
4047 selected bib record or its associated copies and call_numbers/,
4049 { desc => 'Bib ID', type => 'number' },
4050 { desc => q/Optional arguments. Supported arguments include:
4051 "pickup_lib_descendant" -> limit holds to those whose pickup
4052 library is equal to or is a child of the provided org unit/,
4056 return => {desc => 'Hold count', type => 'number'}
4060 __PACKAGE__->register_method(
4061 method => 'rec_hold_count',
4062 api_name => 'open-ils.circ.mmr.holds.count',
4064 desc => q/Returns the total number of holds that target the
4065 selected metarecord or its associated copies, call_numbers, and bib records/,
4067 { desc => 'Metarecord ID', type => 'number' },
4069 return => {desc => 'Hold count', type => 'number'}
4073 # XXX Need to add type I (and, soon, type P) holds to these counts
4074 sub rec_hold_count {
4075 my($self, $conn, $target_id, $args) = @_;
4082 filter => {metarecord => $target_id}
4089 filter => { id => $target_id },
4094 if($self->api_name =~ /mmr/) {
4095 delete $bre_join->{bre}->{filter};
4096 $bre_join->{bre}->{join} = $mmr_join;
4102 fkey => 'call_number',
4108 select => {ahr => [{column => 'id', transform => 'count', alias => 'count'}]},
4112 cancel_time => undef,
4113 fulfillment_time => undef,
4117 hold_type => [qw/C F R/],
4120 select => {acp => ['id']},
4121 from => { acp => $cn_join }
4131 select => {acn => ['id']},
4132 from => {acn => $bre_join}
4140 target => $target_id
4148 if($self->api_name =~ /mmr/) {
4149 $query->{where}->{'+ahr'}->{'-or'}->[2] = {
4154 select => {bre => ['id']},
4155 from => {bre => $mmr_join}
4161 $query->{where}->{'+ahr'}->{'-or'}->[3] = {
4164 target => $target_id
4170 if (my $pld = $args->{pickup_lib_descendant}) {
4172 my $top_ou = new_editor()->search_actor_org_unit(
4173 {parent_ou => undef}
4174 )->[0]; # XXX Assumes single root node. Not alone in this...
4176 $query->{where}->{'+ahr'}->{pickup_lib} = {
4178 select => {aou => [{
4180 transform => 'actor.org_unit_descendants',
4181 result_field => 'id'
4184 where => {id => $pld}
4186 } if ($pld != $top_ou->id);
4190 return new_editor()->json_query($query)->[0]->{count};
4193 # A helper function to calculate a hold's expiration time at a given
4194 # org_unit. Takes the org_unit as an argument and returns either the
4195 # hold expire time as an ISO8601 string or undef if there is no hold
4196 # expiration interval set for the subject ou.
4197 sub calculate_expire_time
4200 my $interval = $U->ou_ancestor_setting_value($ou, OILS_SETTING_HOLD_EXPIRE);
4202 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
4203 return $U->epoch2ISO8601($date->epoch);