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 my $apputils = "OpenILS::Application::AppUtils";
42 __PACKAGE__->register_method(
43 method => "test_and_create_hold_batch",
44 api_name => "open-ils.circ.holds.test_and_create.batch",
47 desc => q/This is for batch creating a set of holds where every field is identical except for the targets./,
49 { desc => 'Authentication token', type => 'string' },
50 { 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'},
51 { desc => 'Array of target ids', type => 'array' }
54 desc => 'Array of hold ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
59 __PACKAGE__->register_method(
60 method => "test_and_create_hold_batch",
61 api_name => "open-ils.circ.holds.test_and_create.batch.override",
64 desc => '@see open-ils.circ.holds.test_and_create.batch',
69 sub test_and_create_hold_batch {
70 my( $self, $conn, $auth, $params, $target_list, $oargs ) = @_;
73 if ($self->api_name =~ /override/) {
75 $oargs = { all => 1 } unless defined $oargs;
76 $$params{oargs} = $oargs; # for is_possible checking.
79 my $e = new_editor(authtoken=>$auth);
80 return $e->die_event unless $e->checkauth;
81 $$params{'requestor'} = $e->requestor->id;
84 if ($$params{'hold_type'} eq 'T') { $target_field = 'titleid'; }
85 elsif ($$params{'hold_type'} eq 'C') { $target_field = 'copy_id'; }
86 elsif ($$params{'hold_type'} eq 'R') { $target_field = 'copy_id'; }
87 elsif ($$params{'hold_type'} eq 'F') { $target_field = 'copy_id'; }
88 elsif ($$params{'hold_type'} eq 'I') { $target_field = 'issuanceid'; }
89 elsif ($$params{'hold_type'} eq 'V') { $target_field = 'volume_id'; }
90 elsif ($$params{'hold_type'} eq 'M') { $target_field = 'mrid'; }
91 elsif ($$params{'hold_type'} eq 'P') { $target_field = 'partid'; }
92 else { return undef; }
94 foreach (@$target_list) {
95 $$params{$target_field} = $_;
97 ($res) = $self->method_lookup(
98 'open-ils.circ.title_hold.is_possible')->run($auth, $params, $override ? $oargs : {});
99 if ($res->{'success'} == 1) {
101 $params->{'depth'} = $res->{'depth'} if $res->{'depth'};
103 # Remove oargs from params so holds can be created.
104 if ($$params{oargs}) {
105 delete $$params{oargs};
108 my $ahr = construct_hold_request_object($params);
109 my ($res2) = $self->method_lookup(
111 ? 'open-ils.circ.holds.create.override'
112 : 'open-ils.circ.holds.create'
113 )->run($auth, $ahr, $oargs);
115 'target' => $$params{$target_field},
118 $conn->respond($res2);
121 'target' => $$params{$target_field},
124 $conn->respond($res);
130 sub construct_hold_request_object {
133 my $ahr = Fieldmapper::action::hold_request->new;
136 foreach my $field (keys %{ $params }) {
137 if ($field eq 'depth') { $ahr->selection_depth($$params{$field}); }
138 elsif ($field eq 'patronid') {
139 $ahr->usr($$params{$field}); }
140 elsif ($field eq 'titleid') { $ahr->target($$params{$field}); }
141 elsif ($field eq 'copy_id') { $ahr->target($$params{$field}); }
142 elsif ($field eq 'issuanceid') { $ahr->target($$params{$field}); }
143 elsif ($field eq 'volume_id') { $ahr->target($$params{$field}); }
144 elsif ($field eq 'mrid') { $ahr->target($$params{$field}); }
145 elsif ($field eq 'partid') { $ahr->target($$params{$field}); }
147 $ahr->$field($$params{$field});
153 __PACKAGE__->register_method(
154 method => "create_hold_batch",
155 api_name => "open-ils.circ.holds.create.batch",
158 desc => q/@see open-ils.circ.holds.create.batch/,
160 { desc => 'Authentication token', type => 'string' },
161 { desc => 'Array of hold objects', type => 'array' }
164 desc => 'Array of hold ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
169 __PACKAGE__->register_method(
170 method => "create_hold_batch",
171 api_name => "open-ils.circ.holds.create.override.batch",
174 desc => '@see open-ils.circ.holds.create.batch',
179 sub create_hold_batch {
180 my( $self, $conn, $auth, $hold_list, $oargs ) = @_;
181 (my $method = $self->api_name) =~ s/\.batch//og;
182 foreach (@$hold_list) {
183 my ($res) = $self->method_lookup($method)->run($auth, $_, $oargs);
184 $conn->respond($res);
190 __PACKAGE__->register_method(
191 method => "create_hold",
192 api_name => "open-ils.circ.holds.create",
194 desc => "Create a new hold for an item. From a permissions perspective, " .
195 "the login session is used as the 'requestor' of the hold. " .
196 "The hold recipient is determined by the 'usr' setting within the hold object. " .
197 'First we verify the requestor has holds request permissions. ' .
198 'Then we verify that the recipient is allowed to make the given hold. ' .
199 'If not, we see if the requestor has "override" capabilities. If not, ' .
200 'a permission exception is returned. If permissions allow, we cycle ' .
201 'through the set of holds objects and create. ' .
202 'If the recipient does not have permission to place multiple holds ' .
203 'on a single title and said operation is attempted, a permission ' .
204 'exception is returned',
206 { desc => 'Authentication token', type => 'string' },
207 { desc => 'Hold object for hold to be created',
208 type => 'object', class => 'ahr' }
211 desc => 'New ahr ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
216 __PACKAGE__->register_method(
217 method => "create_hold",
218 api_name => "open-ils.circ.holds.create.override",
219 notes => '@see open-ils.circ.holds.create',
221 desc => "If the recipient is not allowed to receive the requested hold, " .
222 "call this method to attempt the override",
224 { desc => 'Authentication token', type => 'string' },
226 desc => 'Hold object for hold to be created',
227 type => 'object', class => 'ahr'
231 desc => 'New hold (ahr) ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
237 my( $self, $conn, $auth, $hold, $oargs ) = @_;
238 return -1 unless $hold;
239 my $e = new_editor(authtoken=>$auth, xact=>1);
240 return $e->die_event unless $e->checkauth;
243 if ($self->api_name =~ /override/) {
245 $oargs = { all => 1 } unless defined $oargs;
250 my $requestor = $e->requestor;
251 my $recipient = $requestor;
253 if( $requestor->id ne $hold->usr ) {
254 # Make sure the requestor is allowed to place holds for
255 # the recipient if they are not the same people
256 $recipient = $e->retrieve_actor_user($hold->usr) or return $e->die_event;
257 $e->allowed('REQUEST_HOLDS', $recipient->home_ou) or return $e->die_event;
260 # If the related org setting tells us to, block if patron privs have expired
261 my $expire_setting = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_BLOCK_HOLD_FOR_EXPIRED_PATRON);
262 if ($expire_setting) {
263 my $expire = DateTime::Format::ISO8601->new->parse_datetime(
264 cleanse_ISO8601($recipient->expire_date));
266 push( @events, OpenILS::Event->new(
267 'PATRON_ACCOUNT_EXPIRED',
268 "payload" => {"fail_part" => "actor.usr.privs_expired"}
269 )) if( CORE::time > $expire->epoch ) ;
272 # Now make sure the recipient is allowed to receive the specified hold
273 my $porg = $recipient->home_ou;
274 my $rid = $e->requestor->id;
275 my $t = $hold->hold_type;
277 # See if a duplicate hold already exists
279 usr => $recipient->id,
281 fulfillment_time => undef,
282 target => $hold->target,
283 cancel_time => undef,
286 $sargs->{holdable_formats} = $hold->holdable_formats if $t eq 'M';
288 my $existing = $e->search_action_hold_request($sargs);
289 push( @events, OpenILS::Event->new('HOLD_EXISTS')) if @$existing;
291 my $checked_out = hold_item_is_checked_out($e, $recipient->id, $hold->hold_type, $hold->target);
292 push( @events, OpenILS::Event->new('HOLD_ITEM_CHECKED_OUT')) if $checked_out;
294 if ( $t eq OILS_HOLD_TYPE_METARECORD ) {
295 return $e->die_event unless $e->allowed('MR_HOLDS', $porg);
296 } elsif ( $t eq OILS_HOLD_TYPE_TITLE ) {
297 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
298 } elsif ( $t eq OILS_HOLD_TYPE_VOLUME ) {
299 return $e->die_event unless $e->allowed('VOLUME_HOLDS', $porg);
300 } elsif ( $t eq OILS_HOLD_TYPE_MONOPART ) {
301 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
302 } elsif ( $t eq OILS_HOLD_TYPE_ISSUANCE ) {
303 return $e->die_event unless $e->allowed('ISSUANCE_HOLDS', $porg);
304 } elsif ( $t eq OILS_HOLD_TYPE_COPY ) {
305 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
306 } elsif ( $t eq OILS_HOLD_TYPE_FORCE || $t eq OILS_HOLD_TYPE_RECALL ) {
307 my $copy = $e->retrieve_asset_copy($hold->target)
308 or return $e->die_event;
309 if ( $t eq OILS_HOLD_TYPE_FORCE ) {
310 return $e->die_event unless $e->allowed('COPY_HOLDS_FORCE', $copy->circ_lib);
311 } elsif ( $t eq OILS_HOLD_TYPE_RECALL ) {
312 return $e->die_event unless $e->allowed('COPY_HOLDS_RECALL', $copy->circ_lib);
321 for my $evt (@events) {
323 my $name = $evt->{textcode};
324 if($oargs->{all} || grep { $_ eq $name } @{$oargs->{events}}) {
325 return $e->die_event unless $e->allowed("$name.override", $porg);
333 # set the configured expire time
334 unless($hold->expire_time) {
335 my $interval = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_HOLD_EXPIRE);
337 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
338 $hold->expire_time($U->epoch2ISO8601($date->epoch));
342 $hold->requestor($e->requestor->id);
343 $hold->request_lib($e->requestor->ws_ou);
344 $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
345 $hold = $e->create_action_hold_request($hold) or return $e->die_event;
349 $conn->respond_complete($hold->id);
352 'open-ils.storage.action.hold_request.copy_targeter',
353 undef, $hold->id ) unless $U->is_true($hold->frozen);
358 # makes sure that a user has permission to place the type of requested hold
359 # returns the Perm exception if not allowed, returns undef if all is well
360 sub _check_holds_perm {
361 my($type, $user_id, $org_id) = @_;
365 $evt = $apputils->check_perms($user_id, $org_id, "MR_HOLDS" );
366 } elsif ($type eq "T") {
367 $evt = $apputils->check_perms($user_id, $org_id, "TITLE_HOLDS" );
368 } elsif($type eq "V") {
369 $evt = $apputils->check_perms($user_id, $org_id, "VOLUME_HOLDS");
370 } elsif($type eq "C") {
371 $evt = $apputils->check_perms($user_id, $org_id, "COPY_HOLDS" );
378 # tests if the given user is allowed to place holds on another's behalf
379 sub _check_request_holds_perm {
382 if (my $evt = $apputils->check_perms(
383 $user_id, $org_id, "REQUEST_HOLDS")) {
388 my $ses_is_req_note = 'The login session is the requestor. If the requestor is different from the user, ' .
389 'then the requestor must have VIEW_HOLD permissions';
391 __PACKAGE__->register_method(
392 method => "retrieve_holds_by_id",
393 api_name => "open-ils.circ.holds.retrieve_by_id",
395 desc => "Retrieve the hold, with hold transits attached, for the specified ID. $ses_is_req_note",
397 { desc => 'Authentication token', type => 'string' },
398 { desc => 'Hold ID', type => 'number' }
401 desc => 'Hold object with transits attached, event on error',
407 sub retrieve_holds_by_id {
408 my($self, $client, $auth, $hold_id) = @_;
409 my $e = new_editor(authtoken=>$auth);
410 $e->checkauth or return $e->event;
411 $e->allowed('VIEW_HOLD') or return $e->event;
413 my $holds = $e->search_action_hold_request(
415 { id => $hold_id , fulfillment_time => undef },
417 order_by => { ahr => "request_time" },
419 flesh_fields => {ahr => ['notes']}
424 flesh_hold_transits($holds);
425 flesh_hold_notices($holds, $e);
430 __PACKAGE__->register_method(
431 method => "retrieve_holds",
432 api_name => "open-ils.circ.holds.retrieve",
434 desc => "Retrieves all the holds, with hold transits attached, for the specified user. $ses_is_req_note",
436 { desc => 'Authentication token', type => 'string' },
437 { desc => 'User ID', type => 'integer' }
440 desc => 'list of holds, event on error',
445 __PACKAGE__->register_method(
446 method => "retrieve_holds",
447 api_name => "open-ils.circ.holds.id_list.retrieve",
450 desc => "Retrieves all the hold IDs, for the specified user. $ses_is_req_note",
452 { desc => 'Authentication token', type => 'string' },
453 { desc => 'User ID', type => 'integer' }
456 desc => 'list of holds, event on error',
461 __PACKAGE__->register_method(
462 method => "retrieve_holds",
463 api_name => "open-ils.circ.holds.canceled.retrieve",
466 desc => "Retrieves all the cancelled holds for the specified user. $ses_is_req_note",
468 { desc => 'Authentication token', type => 'string' },
469 { desc => 'User ID', type => 'integer' }
472 desc => 'list of holds, event on error',
477 __PACKAGE__->register_method(
478 method => "retrieve_holds",
479 api_name => "open-ils.circ.holds.canceled.id_list.retrieve",
482 desc => "Retrieves list of cancelled hold IDs for the specified user. $ses_is_req_note",
484 { desc => 'Authentication token', type => 'string' },
485 { desc => 'User ID', type => 'integer' }
488 desc => 'list of hold IDs, event on error',
495 my ($self, $client, $auth, $user_id) = @_;
497 my $e = new_editor(authtoken=>$auth);
498 return $e->event unless $e->checkauth;
499 $user_id = $e->requestor->id unless defined $user_id;
501 my $notes_filter = {staff => 'f'};
502 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
503 unless($user_id == $e->requestor->id) {
504 if($e->allowed('VIEW_HOLD', $user->home_ou)) {
505 $notes_filter = {staff => 't'}
507 my $allowed = OpenILS::Application::Actor::Friends->friend_perm_allowed(
508 $e, $user_id, $e->requestor->id, 'hold.view');
509 return $e->event unless $allowed;
512 # staff member looking at his/her own holds can see staff and non-staff notes
513 $notes_filter = {} if $e->allowed('VIEW_HOLD', $user->home_ou);
517 select => {ahr => ['id']},
519 where => {usr => $user_id, fulfillment_time => undef}
522 if($self->api_name =~ /canceled/) {
524 # Fetch the canceled holds
525 # order cancelled holds by cancel time, most recent first
527 $holds_query->{order_by} = [{class => 'ahr', field => 'cancel_time', direction => 'desc'}];
530 my $cancel_count = $U->ou_ancestor_setting_value(
531 $e->requestor->ws_ou, 'circ.holds.canceled.display_count', $e);
533 unless($cancel_count) {
534 $cancel_age = $U->ou_ancestor_setting_value(
535 $e->requestor->ws_ou, 'circ.holds.canceled.display_age', $e);
537 # if no settings are defined, default to last 10 cancelled holds
538 $cancel_count = 10 unless $cancel_age;
541 if($cancel_count) { # limit by count
543 $holds_query->{where}->{cancel_time} = {'!=' => undef};
544 $holds_query->{limit} = $cancel_count;
546 } elsif($cancel_age) { # limit by age
548 # find all of the canceled holds that were canceled within the configured time frame
549 my $date = DateTime->now->subtract(seconds => OpenSRF::Utils::interval_to_seconds($cancel_age));
550 $date = $U->epoch2ISO8601($date->epoch);
551 $holds_query->{where}->{cancel_time} = {'>=' => $date};
556 # order non-cancelled holds by ready-for-pickup, then active, followed by suspended
557 # "compare" sorts false values to the front. testing pickup_lib != current_shelf_lib
558 # will sort by pl = csl > pl != csl > followed by csl is null;
559 $holds_query->{order_by} = [
561 field => 'pickup_lib',
562 compare => {'!=' => {'+ahr' => 'current_shelf_lib'}}},
563 {class => 'ahr', field => 'shelf_time'},
564 {class => 'ahr', field => 'frozen'},
565 {class => 'ahr', field => 'request_time'}
568 $holds_query->{where}->{cancel_time} = undef;
571 my $hold_ids = $e->json_query($holds_query);
572 $hold_ids = [ map { $_->{id} } @$hold_ids ];
574 return $hold_ids if $self->api_name =~ /id_list/;
577 for my $hold_id ( @$hold_ids ) {
579 my $hold = $e->retrieve_action_hold_request($hold_id);
580 $hold->notes($e->search_action_hold_request_note({hold => $hold_id, %$notes_filter}));
583 $e->search_action_hold_transit_copy([
585 {order_by => {ahtc => 'source_send_time desc'}, limit => 1}])->[0]
595 __PACKAGE__->register_method(
596 method => 'user_hold_count',
597 api_name => 'open-ils.circ.hold.user.count'
600 sub user_hold_count {
601 my ( $self, $conn, $auth, $userid ) = @_;
602 my $e = new_editor( authtoken => $auth );
603 return $e->event unless $e->checkauth;
604 my $patron = $e->retrieve_actor_user($userid)
606 return $e->event unless $e->allowed( 'VIEW_HOLD', $patron->home_ou );
607 return __user_hold_count( $self, $e, $userid );
610 sub __user_hold_count {
611 my ( $self, $e, $userid ) = @_;
612 my $holds = $e->search_action_hold_request(
615 fulfillment_time => undef,
616 cancel_time => undef,
621 return scalar(@$holds);
625 __PACKAGE__->register_method(
626 method => "retrieve_holds_by_pickup_lib",
627 api_name => "open-ils.circ.holds.retrieve_by_pickup_lib",
629 "Retrieves all the holds, with hold transits attached, for the specified pickup_ou id."
632 __PACKAGE__->register_method(
633 method => "retrieve_holds_by_pickup_lib",
634 api_name => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
635 notes => "Retrieves all the hold ids for the specified pickup_ou id. "
638 sub retrieve_holds_by_pickup_lib {
639 my ($self, $client, $login_session, $ou_id) = @_;
641 #FIXME -- put an appropriate permission check here
642 #my( $user, $target, $evt ) = $apputils->checkses_requestor(
643 # $login_session, $user_id, 'VIEW_HOLD' );
644 #return $evt if $evt;
646 my $holds = $apputils->simplereq(
648 "open-ils.cstore.direct.action.hold_request.search.atomic",
650 pickup_lib => $ou_id ,
651 fulfillment_time => undef,
654 { order_by => { ahr => "request_time" } }
657 if ( ! $self->api_name =~ /id_list/ ) {
658 flesh_hold_transits($holds);
662 return [ map { $_->id } @$holds ];
666 __PACKAGE__->register_method(
667 method => "uncancel_hold",
668 api_name => "open-ils.circ.hold.uncancel"
672 my($self, $client, $auth, $hold_id) = @_;
673 my $e = new_editor(authtoken=>$auth, xact=>1);
674 return $e->die_event unless $e->checkauth;
676 my $hold = $e->retrieve_action_hold_request($hold_id)
677 or return $e->die_event;
678 return $e->die_event unless $e->allowed('CANCEL_HOLDS', $hold->request_lib);
680 if ($hold->fulfillment_time) {
684 unless ($hold->cancel_time) {
689 # if configured to reset the request time, also reset the expire time
690 if($U->ou_ancestor_setting_value(
691 $hold->request_lib, 'circ.holds.uncancel.reset_request_time', $e)) {
693 $hold->request_time('now');
694 my $interval = $U->ou_ancestor_setting_value($hold->request_lib, OILS_SETTING_HOLD_EXPIRE);
696 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
697 $hold->expire_time($U->epoch2ISO8601($date->epoch));
701 $hold->clear_cancel_time;
702 $hold->clear_cancel_cause;
703 $hold->clear_cancel_note;
704 $hold->clear_shelf_time;
705 $hold->clear_current_copy;
706 $hold->clear_capture_time;
707 $hold->clear_prev_check_time;
708 $hold->clear_shelf_expire_time;
709 $hold->clear_current_shelf_lib;
711 $e->update_action_hold_request($hold) or return $e->die_event;
714 $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
720 __PACKAGE__->register_method(
721 method => "cancel_hold",
722 api_name => "open-ils.circ.hold.cancel",
724 desc => 'Cancels the specified hold. The login session is the requestor. If the requestor is different from the usr field ' .
725 'on the hold, the requestor must have CANCEL_HOLDS permissions. The hold may be either the hold object or the hold id',
727 {desc => 'Authentication token', type => 'string'},
728 {desc => 'Hold ID', type => 'number'},
729 {desc => 'Cause of Cancellation', type => 'string'},
730 {desc => 'Note', type => 'string'}
733 desc => '1 on success, event on error'
739 my($self, $client, $auth, $holdid, $cause, $note) = @_;
741 my $e = new_editor(authtoken=>$auth, xact=>1);
742 return $e->die_event unless $e->checkauth;
744 my $hold = $e->retrieve_action_hold_request($holdid)
745 or return $e->die_event;
747 if( $e->requestor->id ne $hold->usr ) {
748 return $e->die_event unless $e->allowed('CANCEL_HOLDS');
751 if ($hold->cancel_time) {
756 # If the hold is captured, reset the copy status
757 if( $hold->capture_time and $hold->current_copy ) {
759 my $copy = $e->retrieve_asset_copy($hold->current_copy)
760 or return $e->die_event;
762 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
763 $logger->info("canceling hold $holdid whose item is on the holds shelf");
764 # $logger->info("setting copy to status 'reshelving' on hold cancel");
765 # $copy->status(OILS_COPY_STATUS_RESHELVING);
766 # $copy->editor($e->requestor->id);
767 # $copy->edit_date('now');
768 # $e->update_asset_copy($copy) or return $e->event;
770 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
773 $logger->warn("! canceling hold [$hid] that is in transit");
774 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
777 my $trans = $e->retrieve_action_transit_copy($transid);
778 # Leave the transit alive, but set the copy status to
779 # reshelving so it will be properly reshelved when it gets back home
781 $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
782 $e->update_action_transit_copy($trans) or return $e->die_event;
788 $hold->cancel_time('now');
789 $hold->cancel_cause($cause);
790 $hold->cancel_note($note);
791 $e->update_action_hold_request($hold)
792 or return $e->die_event;
794 delete_hold_copy_maps($self, $e, $hold->id);
798 # re-fetch the hold to pick up the real cancel_time (not "now") for A/T
800 $hold = $e->retrieve_action_hold_request($hold->id) or return $e->die_event;
803 if ($e->requestor->id == $hold->usr) {
804 $U->create_events_for_hook('hold_request.cancel.patron', $hold, $hold->pickup_lib);
806 $U->create_events_for_hook('hold_request.cancel.staff', $hold, $hold->pickup_lib);
812 sub delete_hold_copy_maps {
817 my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
819 $editor->delete_action_hold_copy_map($_)
820 or return $editor->event;
826 my $update_hold_desc = 'The login session is the requestor. ' .
827 'If the requestor is different from the usr field on the hold, ' .
828 'the requestor must have UPDATE_HOLDS permissions. ' .
829 'If supplying a hash of hold data, "id" must be included. ' .
830 'The hash is ignored if a hold object is supplied, ' .
831 'so you should supply only one kind of hold data argument.' ;
833 __PACKAGE__->register_method(
834 method => "update_hold",
835 api_name => "open-ils.circ.hold.update",
837 desc => "Updates the specified hold. $update_hold_desc",
839 {desc => 'Authentication token', type => 'string'},
840 {desc => 'Hold Object', type => 'object'},
841 {desc => 'Hash of values to be applied', type => 'object'}
844 desc => 'Hold ID on success, event on error',
850 __PACKAGE__->register_method(
851 method => "batch_update_hold",
852 api_name => "open-ils.circ.hold.update.batch",
855 desc => "Updates the specified hold(s). $update_hold_desc",
857 {desc => 'Authentication token', type => 'string'},
858 {desc => 'Array of hold obejcts', type => 'array' },
859 {desc => 'Array of hashes of values to be applied', type => 'array' }
862 desc => 'Hold ID per success, event per error',
868 my($self, $client, $auth, $hold, $values) = @_;
869 my $e = new_editor(authtoken=>$auth, xact=>1);
870 return $e->die_event unless $e->checkauth;
871 my $resp = update_hold_impl($self, $e, $hold, $values);
872 if ($U->event_code($resp)) {
876 $e->commit; # FIXME: update_hold_impl already does $e->commit ??
880 sub batch_update_hold {
881 my($self, $client, $auth, $hold_list, $values_list) = @_;
882 my $e = new_editor(authtoken=>$auth);
883 return $e->die_event unless $e->checkauth;
885 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.
887 $values_list ||= []; # FIXME: either move this above $count declaration, or send an event if both lists undef. Probably the latter.
889 # FIXME: Failing over to [] guarantees warnings for "Use of unitialized value" in update_hold_impl call.
890 # FIXME: We should be sure we only call update_hold_impl with hold object OR hash, not both.
892 for my $idx (0..$count-1) {
894 my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
895 $e->xact_commit unless $U->event_code($resp);
896 $client->respond($resp);
900 return undef; # not in the register return type, assuming we should always have at least one list populated
903 sub update_hold_impl {
904 my($self, $e, $hold, $values) = @_;
906 my $need_retarget = 0;
909 $hold = $e->retrieve_action_hold_request($values->{id})
910 or return $e->die_event;
911 for my $k (keys %$values) {
912 # Outside of pickup_lib (covered by the first regex) I don't know when these would currently change.
913 # But hey, why not cover things that may happen later?
914 if ($k =~ '_(lib|ou)$' || $k eq 'target' || $k eq 'hold_type' || $k eq 'requestor' || $k eq 'selection_depth' || $k eq 'holdable_formats') {
915 if (defined $values->{$k} && defined $hold->$k() && $values->{$k} ne $hold->$k()) {
916 # Value changed? RETARGET!
918 } elsif (defined $hold->$k() != defined $values->{$k}) {
919 # Value being set or cleared? RETARGET!
923 if (defined $values->{$k}) {
924 $hold->$k($values->{$k});
926 my $f = "clear_$k"; $hold->$f();
931 my $orig_hold = $e->retrieve_action_hold_request($hold->id)
932 or return $e->die_event;
934 # don't allow the user to be changed
935 return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
937 if($hold->usr ne $e->requestor->id) {
938 # if the hold is for a different user, make sure the
939 # requestor has the appropriate permissions
940 my $usr = $e->retrieve_actor_user($hold->usr)
941 or return $e->die_event;
942 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
946 # --------------------------------------------------------------
947 # Changing the request time is like playing God
948 # --------------------------------------------------------------
949 if($hold->request_time ne $orig_hold->request_time) {
950 return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
951 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
955 # --------------------------------------------------------------
956 # Code for making sure staff have appropriate permissons for cut_in_line
957 # This, as is, doesn't prevent a user from cutting their own holds in line
959 # --------------------------------------------------------------
960 if($U->is_true($hold->cut_in_line) ne $U->is_true($orig_hold->cut_in_line)) {
961 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
965 # --------------------------------------------------------------
966 # Disallow hold suspencion if the hold is already captured.
967 # --------------------------------------------------------------
968 if ($U->is_true($hold->frozen) and not $U->is_true($orig_hold->frozen)) {
969 $hold_status = _hold_status($e, $hold);
970 if ($hold_status > 2 && $hold_status != 7) { # hold is captured
971 $logger->info("bypassing hold freeze on captured hold");
972 return OpenILS::Event->new('HOLD_SUSPEND_AFTER_CAPTURE');
977 # --------------------------------------------------------------
978 # if the hold is on the holds shelf or in transit and the pickup
979 # lib changes we need to create a new transit.
980 # --------------------------------------------------------------
981 if($orig_hold->pickup_lib ne $hold->pickup_lib) {
983 $hold_status = _hold_status($e, $hold) unless $hold_status;
985 if($hold_status == 3) { # in transit
987 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
988 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
990 $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
992 # update the transit to reflect the new pickup location
993 my $transit = $e->search_action_hold_transit_copy(
994 {hold=>$hold->id, dest_recv_time => undef})->[0]
995 or return $e->die_event;
997 $transit->prev_dest($transit->dest); # mark the previous destination on the transit
998 $transit->dest($hold->pickup_lib);
999 $e->update_action_hold_transit_copy($transit) or return $e->die_event;
1001 } elsif($hold_status == 4 or $hold_status == 5 or $hold_status == 8) { # on holds shelf
1003 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
1004 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
1006 $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
1008 if ($hold->pickup_lib eq $orig_hold->current_shelf_lib) {
1009 # This can happen if the pickup lib is changed while the hold is
1010 # on the shelf, then changed back to the original pickup lib.
1011 # Restore the original shelf_expire_time to prevent abuse.
1012 set_hold_shelf_expire_time(undef, $hold, $e, $hold->shelf_time);
1015 # clear to prevent premature shelf expiration
1016 $hold->clear_shelf_expire_time;
1021 if($U->is_true($hold->frozen)) {
1022 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
1023 $hold->clear_current_copy;
1024 $hold->clear_prev_check_time;
1027 $e->update_action_hold_request($hold) or return $e->die_event;
1030 if(!$U->is_true($hold->frozen) && $U->is_true($orig_hold->frozen)) {
1031 $logger->info("Running targeter on activated hold ".$hold->id);
1032 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1035 # a change to mint-condition changes the set of potential copies, so retarget the hold;
1036 if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
1037 _reset_hold($self, $e->requestor, $hold)
1038 } elsif($need_retarget && !defined $hold->capture_time()) { # If needed, retarget the hold due to changes
1040 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1046 # this does not update the hold in the DB. It only
1047 # sets the shelf_expire_time field on the hold object.
1048 # start_time is optional and defaults to 'now'
1049 sub set_hold_shelf_expire_time {
1050 my ($class, $hold, $editor, $start_time) = @_;
1052 my $shelf_expire = $U->ou_ancestor_setting_value(
1054 'circ.holds.default_shelf_expire_interval',
1058 return undef unless $shelf_expire;
1060 $start_time = ($start_time) ?
1061 DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time)) :
1064 my $seconds = OpenSRF::Utils->interval_to_seconds($shelf_expire);
1065 my $expire_time = $start_time->add(seconds => $seconds);
1067 # if the shelf expire time overlaps with a pickup lib's
1068 # closed date, push it out to the first open date
1069 my $dateinfo = $U->storagereq(
1070 'open-ils.storage.actor.org_unit.closed_date.overlap',
1071 $hold->pickup_lib, $expire_time->strftime('%FT%T%z'));
1074 my $dt_parser = DateTime::Format::ISO8601->new;
1075 $expire_time = $dt_parser->parse_datetime(cleanse_ISO8601($dateinfo->{end}));
1077 # TODO: enable/disable time bump via setting?
1078 $expire_time->set(hour => '23', minute => '59', second => '59');
1080 $logger->info("circulator: shelf_expire_time overlaps".
1081 " with closed date, pushing expire time to $expire_time");
1084 $hold->shelf_expire_time($expire_time->strftime('%FT%T%z'));
1090 my($e, $orig_hold, $hold, $copy) = @_;
1091 my $src = $orig_hold->pickup_lib;
1092 my $dest = $hold->pickup_lib;
1094 $logger->info("putting hold into transit on pickup_lib update");
1096 my $transit = Fieldmapper::action::hold_transit_copy->new;
1097 $transit->hold($hold->id);
1098 $transit->source($src);
1099 $transit->dest($dest);
1100 $transit->target_copy($copy->id);
1101 $transit->source_send_time('now');
1102 $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
1104 $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
1105 $copy->editor($e->requestor->id);
1106 $copy->edit_date('now');
1108 $e->create_action_hold_transit_copy($transit) or return $e->die_event;
1109 $e->update_asset_copy($copy) or return $e->die_event;
1113 # if the hold is frozen, this method ensures that the hold is not "targeted",
1114 # that is, it clears the current_copy and prev_check_time to essentiallly
1115 # reset the hold. If it is being activated, it runs the targeter in the background
1116 sub update_hold_if_frozen {
1117 my($self, $e, $hold, $orig_hold) = @_;
1118 return if $hold->capture_time;
1120 if($U->is_true($hold->frozen)) {
1121 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
1122 $hold->clear_current_copy;
1123 $hold->clear_prev_check_time;
1126 if($U->is_true($orig_hold->frozen)) {
1127 $logger->info("Running targeter on activated hold ".$hold->id);
1128 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1133 __PACKAGE__->register_method(
1134 method => "hold_note_CUD",
1135 api_name => "open-ils.circ.hold_request.note.cud",
1137 desc => 'Create, update or delete a hold request note. If the operator (from Auth. token) '
1138 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
1140 { desc => 'Authentication token', type => 'string' },
1141 { desc => 'Hold note object', type => 'object' }
1144 desc => 'Returns the note ID, event on error'
1150 my($self, $conn, $auth, $note) = @_;
1152 my $e = new_editor(authtoken => $auth, xact => 1);
1153 return $e->die_event unless $e->checkauth;
1155 my $hold = $e->retrieve_action_hold_request($note->hold)
1156 or return $e->die_event;
1158 if($hold->usr ne $e->requestor->id) {
1159 my $usr = $e->retrieve_actor_user($hold->usr);
1160 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
1161 $note->staff('t') if $note->isnew;
1165 $e->create_action_hold_request_note($note) or return $e->die_event;
1166 } elsif($note->ischanged) {
1167 $e->update_action_hold_request_note($note) or return $e->die_event;
1168 } elsif($note->isdeleted) {
1169 $e->delete_action_hold_request_note($note) or return $e->die_event;
1177 __PACKAGE__->register_method(
1178 method => "retrieve_hold_status",
1179 api_name => "open-ils.circ.hold.status.retrieve",
1181 desc => 'Calculates the current status of the hold. The requestor must have ' .
1182 'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
1184 { desc => 'Hold ID', type => 'number' }
1187 # type => 'number', # event sometimes
1188 desc => <<'END_OF_DESC'
1189 Returns event on error or:
1190 -1 on error (for now),
1191 1 for 'waiting for copy to become available',
1192 2 for 'waiting for copy capture',
1195 5 for 'hold-shelf-delay'
1198 8 for 'captured, on wrong hold shelf'
1204 sub retrieve_hold_status {
1205 my($self, $client, $auth, $hold_id) = @_;
1207 my $e = new_editor(authtoken => $auth);
1208 return $e->event unless $e->checkauth;
1209 my $hold = $e->retrieve_action_hold_request($hold_id)
1210 or return $e->event;
1212 if( $e->requestor->id != $hold->usr ) {
1213 return $e->event unless $e->allowed('VIEW_HOLD');
1216 return _hold_status($e, $hold);
1222 if ($hold->cancel_time) {
1225 if ($U->is_true($hold->frozen) && !$hold->capture_time) {
1228 if ($hold->current_shelf_lib and $hold->current_shelf_lib ne $hold->pickup_lib) {
1231 return 1 unless $hold->current_copy;
1232 return 2 unless $hold->capture_time;
1234 my $copy = $hold->current_copy;
1235 unless( ref $copy ) {
1236 $copy = $e->retrieve_asset_copy($hold->current_copy)
1237 or return $e->event;
1240 return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
1242 if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
1244 my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
1245 return 4 unless $hs_wait_interval;
1247 # if a hold_shelf_status_delay interval is defined and start_time plus
1248 # the interval is greater than now, consider the hold to be in the virtual
1249 # "on its way to the holds shelf" status. Return 5.
1251 my $transit = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
1252 my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
1253 $start_time = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
1254 my $end_time = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
1256 return 5 if $end_time > DateTime->now;
1265 __PACKAGE__->register_method(
1266 method => "retrieve_hold_queue_stats",
1267 api_name => "open-ils.circ.hold.queue_stats.retrieve",
1269 desc => 'Returns summary data about the state of a hold',
1271 { desc => 'Authentication token', type => 'string'},
1272 { desc => 'Hold ID', type => 'number'},
1275 desc => q/Summary object with keys:
1276 total_holds : total holds in queue
1277 queue_position : current queue position
1278 potential_copies : number of potential copies for this hold
1279 estimated_wait : estimated wait time in days
1280 status : hold status
1281 -1 => error or unexpected state,
1282 1 => 'waiting for copy to become available',
1283 2 => 'waiting for copy capture',
1286 5 => 'hold-shelf-delay'
1293 sub retrieve_hold_queue_stats {
1294 my($self, $conn, $auth, $hold_id) = @_;
1295 my $e = new_editor(authtoken => $auth);
1296 return $e->event unless $e->checkauth;
1297 my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1298 if($e->requestor->id != $hold->usr) {
1299 return $e->event unless $e->allowed('VIEW_HOLD');
1301 return retrieve_hold_queue_status_impl($e, $hold);
1304 sub retrieve_hold_queue_status_impl {
1308 # The holds queue is defined as the distinct set of holds that share at
1309 # least one potential copy with the context hold, plus any holds that
1310 # share the same hold type and target. The latter part exists to
1311 # accomodate holds that currently have no potential copies
1312 my $q_holds = $e->json_query({
1314 # fetch cut_in_line and request_time since they're in the order_by
1315 # and we're asking for distinct values
1316 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1320 select => { ahcm => ['hold'] },
1325 'field' => 'target_copy',
1326 'fkey' => 'target_copy'
1330 where => { '+ahcm2' => { hold => $hold->id } },
1337 "field" => "cut_in_line",
1338 "transform" => "coalesce",
1340 "direction" => "desc"
1342 { "class" => "ahr", "field" => "request_time" }
1347 if (!@$q_holds) { # none? maybe we don't have a map ...
1348 $q_holds = $e->json_query({
1349 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1354 "field" => "cut_in_line",
1355 "transform" => "coalesce",
1357 "direction" => "desc"
1359 { "class" => "ahr", "field" => "request_time" }
1362 hold_type => $hold->hold_type,
1363 target => $hold->target,
1364 capture_time => undef,
1365 cancel_time => undef,
1367 {expire_time => undef },
1368 {expire_time => {'>' => 'now'}}
1376 for my $h (@$q_holds) {
1377 last if $h->{id} == $hold->id;
1381 my $hold_data = $e->json_query({
1383 acp => [ {column => 'id', transform => 'count', aggregate => 1, alias => 'count'} ],
1384 ccm => [ {column =>'avg_wait_time'} ]
1390 ccm => {type => 'left'}
1395 where => {'+ahcm' => {hold => $hold->id} }
1398 my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1400 my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1401 my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1402 $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1403 $default_wait ||= '0 seconds';
1405 # Estimated wait time is the average wait time across the set
1406 # of potential copies, divided by the number of potential copies
1407 # times the queue position.
1409 my $combined_secs = 0;
1410 my $num_potentials = 0;
1412 for my $wait_data (@$hold_data) {
1413 my $count += $wait_data->{count};
1414 $combined_secs += $count *
1415 OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1416 $num_potentials += $count;
1419 my $estimated_wait = -1;
1421 if($num_potentials) {
1422 my $avg_wait = $combined_secs / $num_potentials;
1423 $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1424 $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1428 total_holds => scalar(@$q_holds),
1429 queue_position => $qpos,
1430 potential_copies => $num_potentials,
1431 status => _hold_status( $e, $hold ),
1432 estimated_wait => int($estimated_wait)
1437 sub fetch_open_hold_by_current_copy {
1440 my $hold = $apputils->simplereq(
1442 'open-ils.cstore.direct.action.hold_request.search.atomic',
1443 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1444 return $hold->[0] if ref($hold);
1448 sub fetch_related_holds {
1451 return $apputils->simplereq(
1453 'open-ils.cstore.direct.action.hold_request.search.atomic',
1454 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1458 __PACKAGE__->register_method(
1459 method => "hold_pull_list",
1460 api_name => "open-ils.circ.hold_pull_list.retrieve",
1462 desc => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1463 'The location is determined by the login session.',
1465 { desc => 'Limit (optional)', type => 'number'},
1466 { desc => 'Offset (optional)', type => 'number'},
1469 desc => 'reference to a list of holds, or event on failure',
1474 __PACKAGE__->register_method(
1475 method => "hold_pull_list",
1476 api_name => "open-ils.circ.hold_pull_list.id_list.retrieve",
1478 desc => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1479 'The location is determined by the login session.',
1481 { desc => 'Limit (optional)', type => 'number'},
1482 { desc => 'Offset (optional)', type => 'number'},
1485 desc => 'reference to a list of holds, or event on failure',
1490 __PACKAGE__->register_method(
1491 method => "hold_pull_list",
1492 api_name => "open-ils.circ.hold_pull_list.retrieve.count",
1494 desc => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1495 'The location is determined by the login session.',
1497 { desc => 'Limit (optional)', type => 'number'},
1498 { desc => 'Offset (optional)', type => 'number'},
1501 desc => 'Holds count (integer), or event on failure',
1508 sub hold_pull_list {
1509 my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1510 my( $reqr, $evt ) = $U->checkses($authtoken);
1511 return $evt if $evt;
1513 my $org = $reqr->ws_ou || $reqr->home_ou;
1514 # the perm locaiton shouldn't really matter here since holds
1515 # will exist all over and VIEW_HOLDS should be universal
1516 $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1517 return $evt if $evt;
1519 if($self->api_name =~ /count/) {
1521 my $count = $U->storagereq(
1522 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1523 $org, $limit, $offset );
1525 $logger->info("Grabbing pull list for org unit $org with $count items");
1528 } elsif( $self->api_name =~ /id_list/ ) {
1529 return $U->storagereq(
1530 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1531 $org, $limit, $offset );
1534 return $U->storagereq(
1535 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1536 $org, $limit, $offset );
1540 __PACKAGE__->register_method(
1541 method => "print_hold_pull_list",
1542 api_name => "open-ils.circ.hold_pull_list.print",
1544 desc => 'Returns an HTML-formatted holds pull list',
1546 { desc => 'Authtoken', type => 'string'},
1547 { desc => 'Org unit ID. Optional, defaults to workstation org unit', type => 'number'},
1550 desc => 'HTML string',
1556 sub print_hold_pull_list {
1557 my($self, $client, $auth, $org_id) = @_;
1559 my $e = new_editor(authtoken=>$auth);
1560 return $e->event unless $e->checkauth;
1562 $org_id = (defined $org_id) ? $org_id : $e->requestor->ws_ou;
1563 return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1565 my $hold_ids = $U->storagereq(
1566 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1569 return undef unless @$hold_ids;
1571 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1573 # Holds will /NOT/ be in order after this ...
1574 my $holds = $e->search_action_hold_request({id => $hold_ids}, {substream => 1});
1575 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1577 # ... so we must resort.
1578 my $hold_map = +{map { $_->id => $_ } @$holds};
1579 my $sorted_holds = [];
1580 push @$sorted_holds, $hold_map->{$_} foreach @$hold_ids;
1582 return $U->fire_object_event(
1583 undef, "ahr.format.pull_list", $sorted_holds,
1584 $org_id, undef, undef, $client
1589 __PACKAGE__->register_method(
1590 method => "print_hold_pull_list_stream",
1592 api_name => "open-ils.circ.hold_pull_list.print.stream",
1594 desc => 'Returns a stream of fleshed holds',
1596 { desc => 'Authtoken', type => 'string'},
1597 { 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)',
1602 desc => 'A stream of fleshed holds',
1608 sub print_hold_pull_list_stream {
1609 my($self, $client, $auth, $params) = @_;
1611 my $e = new_editor(authtoken=>$auth);
1612 return $e->die_event unless $e->checkauth;
1614 delete($$params{org_id}) unless (int($$params{org_id}));
1615 delete($$params{limit}) unless (int($$params{limit}));
1616 delete($$params{offset}) unless (int($$params{offset}));
1617 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1618 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1619 $$params{chunk_size} ||= 10;
1621 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1622 return $e->die_event unless $e->allowed('VIEW_HOLD', $$params{org_id });
1625 if ($$params{sort} && @{ $$params{sort} }) {
1626 for my $s (@{ $$params{sort} }) {
1627 if ($s eq 'acplo.position') {
1629 "class" => "acplo", "field" => "position",
1630 "transform" => "coalesce", "params" => [999]
1632 } elsif ($s eq 'prefix') {
1633 push @$sort, {"class" => "acnp", "field" => "label_sortkey"};
1634 } elsif ($s eq 'call_number') {
1635 push @$sort, {"class" => "acn", "field" => "label_sortkey"};
1636 } elsif ($s eq 'suffix') {
1637 push @$sort, {"class" => "acns", "field" => "label_sortkey"};
1638 } elsif ($s eq 'request_time') {
1639 push @$sort, {"class" => "ahr", "field" => "request_time"};
1643 push @$sort, {"class" => "ahr", "field" => "request_time"};
1646 my $holds_ids = $e->json_query(
1648 "select" => {"ahr" => ["id"]},
1653 "fkey" => "current_copy",
1655 "circ_lib" => $$params{org_id}, "status" => [0,7]
1660 "fkey" => "call_number",
1674 "fkey" => "circ_lib",
1677 "location" => {"=" => {"+acp" => "location"}}
1686 "capture_time" => undef,
1687 "cancel_time" => undef,
1689 {"expire_time" => undef },
1690 {"expire_time" => {">" => "now"}}
1694 (@$sort ? (order_by => $sort) : ()),
1695 ($$params{limit} ? (limit => $$params{limit}) : ()),
1696 ($$params{offset} ? (offset => $$params{offset}) : ())
1697 }, {"substream" => 1}
1698 ) or return $e->die_event;
1700 $logger->info("about to stream back " . scalar(@$holds_ids) . " holds");
1703 for my $hid (@$holds_ids) {
1704 push @chunk, $e->retrieve_action_hold_request([
1708 "ahr" => ["usr", "current_copy"],
1710 "acp" => ["location", "call_number", "parts"],
1711 "acn" => ["record","prefix","suffix"]
1716 if (@chunk >= $$params{chunk_size}) {
1717 $client->respond( \@chunk );
1721 $client->respond_complete( \@chunk ) if (@chunk);
1728 __PACKAGE__->register_method(
1729 method => 'fetch_hold_notify',
1730 api_name => 'open-ils.circ.hold_notification.retrieve_by_hold',
1733 Returns a list of hold notification objects based on hold id.
1734 @param authtoken The loggin session key
1735 @param holdid The id of the hold whose notifications we want to retrieve
1736 @return An array of hold notification objects, event on error.
1740 sub fetch_hold_notify {
1741 my( $self, $conn, $authtoken, $holdid ) = @_;
1742 my( $requestor, $evt ) = $U->checkses($authtoken);
1743 return $evt if $evt;
1744 my ($hold, $patron);
1745 ($hold, $evt) = $U->fetch_hold($holdid);
1746 return $evt if $evt;
1747 ($patron, $evt) = $U->fetch_user($hold->usr);
1748 return $evt if $evt;
1750 $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1751 return $evt if $evt;
1753 $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1754 return $U->cstorereq(
1755 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1759 __PACKAGE__->register_method(
1760 method => 'create_hold_notify',
1761 api_name => 'open-ils.circ.hold_notification.create',
1763 Creates a new hold notification object
1764 @param authtoken The login session key
1765 @param notification The hold notification object to create
1766 @return ID of the new object on success, Event on error
1770 sub create_hold_notify {
1771 my( $self, $conn, $auth, $note ) = @_;
1772 my $e = new_editor(authtoken=>$auth, xact=>1);
1773 return $e->die_event unless $e->checkauth;
1775 my $hold = $e->retrieve_action_hold_request($note->hold)
1776 or return $e->die_event;
1777 my $patron = $e->retrieve_actor_user($hold->usr)
1778 or return $e->die_event;
1780 return $e->die_event unless
1781 $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1783 $note->notify_staff($e->requestor->id);
1784 $e->create_action_hold_notification($note) or return $e->die_event;
1789 __PACKAGE__->register_method(
1790 method => 'create_hold_note',
1791 api_name => 'open-ils.circ.hold_note.create',
1793 Creates a new hold request note object
1794 @param authtoken The login session key
1795 @param note The hold note object to create
1796 @return ID of the new object on success, Event on error
1800 sub create_hold_note {
1801 my( $self, $conn, $auth, $note ) = @_;
1802 my $e = new_editor(authtoken=>$auth, xact=>1);
1803 return $e->die_event unless $e->checkauth;
1805 my $hold = $e->retrieve_action_hold_request($note->hold)
1806 or return $e->die_event;
1807 my $patron = $e->retrieve_actor_user($hold->usr)
1808 or return $e->die_event;
1810 return $e->die_event unless
1811 $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn. Probably want something more specific
1813 $e->create_action_hold_request_note($note) or return $e->die_event;
1818 __PACKAGE__->register_method(
1819 method => 'reset_hold',
1820 api_name => 'open-ils.circ.hold.reset',
1822 Un-captures and un-targets a hold, essentially returning
1823 it to the state it was in directly after it was placed,
1824 then attempts to re-target the hold
1825 @param authtoken The login session key
1826 @param holdid The id of the hold
1832 my( $self, $conn, $auth, $holdid ) = @_;
1834 my ($hold, $evt) = $U->fetch_hold($holdid);
1835 return $evt if $evt;
1836 ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1837 return $evt if $evt;
1838 $evt = _reset_hold($self, $reqr, $hold);
1839 return $evt if $evt;
1844 __PACKAGE__->register_method(
1845 method => 'reset_hold_batch',
1846 api_name => 'open-ils.circ.hold.reset.batch'
1849 sub reset_hold_batch {
1850 my($self, $conn, $auth, $hold_ids) = @_;
1852 my $e = new_editor(authtoken => $auth);
1853 return $e->event unless $e->checkauth;
1855 for my $hold_id ($hold_ids) {
1857 my $hold = $e->retrieve_action_hold_request(
1858 [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}])
1859 or return $e->event;
1861 next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1862 _reset_hold($self, $e->requestor, $hold);
1870 my ($self, $reqr, $hold) = @_;
1872 my $e = new_editor(xact =>1, requestor => $reqr);
1874 $logger->info("reseting hold ".$hold->id);
1876 my $hid = $hold->id;
1878 if( $hold->capture_time and $hold->current_copy ) {
1880 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1881 or return $e->die_event;
1883 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1884 $logger->info("setting copy to status 'reshelving' on hold retarget");
1885 $copy->status(OILS_COPY_STATUS_RESHELVING);
1886 $copy->editor($e->requestor->id);
1887 $copy->edit_date('now');
1888 $e->update_asset_copy($copy) or return $e->die_event;
1890 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1892 # We don't want the copy to remain "in transit"
1893 $copy->status(OILS_COPY_STATUS_RESHELVING);
1894 $logger->warn("! reseting hold [$hid] that is in transit");
1895 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1898 my $trans = $e->retrieve_action_transit_copy($transid);
1900 $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1901 my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1, 1);
1902 $logger->info("Transit abort completed with result $evt");
1903 unless ("$evt" eq 1) {
1912 $hold->clear_capture_time;
1913 $hold->clear_current_copy;
1914 $hold->clear_shelf_time;
1915 $hold->clear_shelf_expire_time;
1916 $hold->clear_current_shelf_lib;
1918 $e->update_action_hold_request($hold) or return $e->die_event;
1922 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1928 __PACKAGE__->register_method(
1929 method => 'fetch_open_title_holds',
1930 api_name => 'open-ils.circ.open_holds.retrieve',
1932 Returns a list ids of un-fulfilled holds for a given title id
1933 @param authtoken The login session key
1934 @param id the id of the item whose holds we want to retrieve
1935 @param type The hold type - M, T, I, V, C, F, R
1939 sub fetch_open_title_holds {
1940 my( $self, $conn, $auth, $id, $type, $org ) = @_;
1941 my $e = new_editor( authtoken => $auth );
1942 return $e->event unless $e->checkauth;
1945 $org ||= $e->requestor->ws_ou;
1947 # return $e->search_action_hold_request(
1948 # { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1950 # XXX make me return IDs in the future ^--
1951 my $holds = $e->search_action_hold_request(
1954 cancel_time => undef,
1956 fulfillment_time => undef
1960 flesh_hold_transits($holds);
1965 sub flesh_hold_transits {
1967 for my $hold ( @$holds ) {
1969 $apputils->simplereq(
1971 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1972 { hold => $hold->id },
1973 { order_by => { ahtc => 'id desc' }, limit => 1 }
1979 sub flesh_hold_notices {
1980 my( $holds, $e ) = @_;
1981 $e ||= new_editor();
1983 for my $hold (@$holds) {
1984 my $notices = $e->search_action_hold_notification(
1986 { hold => $hold->id },
1987 { order_by => { anh => 'notify_time desc' } },
1992 $hold->notify_count(scalar(@$notices));
1994 my $n = $e->retrieve_action_hold_notification($$notices[0])
1995 or return $e->event;
1996 $hold->notify_time($n->notify_time);
2002 __PACKAGE__->register_method(
2003 method => 'fetch_captured_holds',
2004 api_name => 'open-ils.circ.captured_holds.on_shelf.retrieve',
2008 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
2009 @param authtoken The login session key
2010 @param org The org id of the location in question
2011 @param match_copy A specific copy to limit to
2015 __PACKAGE__->register_method(
2016 method => 'fetch_captured_holds',
2017 api_name => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
2021 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
2022 @param authtoken The login session key
2023 @param org The org id of the location in question
2024 @param match_copy A specific copy to limit to
2028 __PACKAGE__->register_method(
2029 method => 'fetch_captured_holds',
2030 api_name => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
2034 Returns list ids of shelf-expired un-fulfilled holds for a given title id
2035 @param authtoken The login session key
2036 @param org The org id of the location in question
2037 @param match_copy A specific copy to limit to
2042 sub fetch_captured_holds {
2043 my( $self, $conn, $auth, $org, $match_copy ) = @_;
2045 my $e = new_editor(authtoken => $auth);
2046 return $e->die_event unless $e->checkauth;
2047 return $e->die_event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
2049 $org ||= $e->requestor->ws_ou;
2051 my $current_copy = { '!=' => undef };
2052 $current_copy = { '=' => $match_copy } if $match_copy;
2055 select => { alhr => ['id'] },
2060 fkey => 'current_copy'
2065 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF, deleted => 'f' },
2067 capture_time => { "!=" => undef },
2068 current_copy => $current_copy,
2069 fulfillment_time => undef,
2070 current_shelf_lib => $org
2074 if($self->api_name =~ /expired/) {
2075 $query->{'where'}->{'+alhr'}->{'-or'} = {
2076 shelf_expire_time => { '<' => 'now'},
2077 cancel_time => { '!=' => undef },
2080 my $hold_ids = $e->json_query( $query );
2082 for my $hold_id (@$hold_ids) {
2083 if($self->api_name =~ /id_list/) {
2084 $conn->respond($hold_id->{id});
2088 $e->retrieve_action_hold_request([
2092 flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
2093 order_by => {anh => 'notify_time desc'}
2103 __PACKAGE__->register_method(
2104 method => "print_expired_holds_stream",
2105 api_name => "open-ils.circ.captured_holds.expired.print.stream",
2109 sub print_expired_holds_stream {
2110 my ($self, $client, $auth, $params) = @_;
2112 # No need to check specific permissions: we're going to call another method
2113 # that will do that.
2114 my $e = new_editor("authtoken" => $auth);
2115 return $e->die_event unless $e->checkauth;
2117 delete($$params{org_id}) unless (int($$params{org_id}));
2118 delete($$params{limit}) unless (int($$params{limit}));
2119 delete($$params{offset}) unless (int($$params{offset}));
2120 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
2121 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
2122 $$params{chunk_size} ||= 10;
2124 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
2126 my @hold_ids = $self->method_lookup(
2127 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
2128 )->run($auth, $params->{"org_id"});
2133 } elsif (defined $U->event_code($hold_ids[0])) {
2135 return $hold_ids[0];
2138 $logger->info("about to stream back up to " . scalar(@hold_ids) . " expired holds");
2141 my @hid_chunk = splice @hold_ids, 0, $params->{"chunk_size"};
2143 my $result_chunk = $e->json_query({
2145 "acp" => ["barcode"],
2147 first_given_name second_given_name family_name alias
2156 "field" => "id", "fkey" => "current_copy",
2159 "field" => "id", "fkey" => "call_number",
2162 "field" => "id", "fkey" => "record"
2166 "acpl" => {"field" => "id", "fkey" => "location"}
2169 "au" => {"field" => "id", "fkey" => "usr"}
2172 "where" => {"+ahr" => {"id" => \@hid_chunk}}
2173 }) or return $e->die_event;
2174 $client->respond($result_chunk);
2181 __PACKAGE__->register_method(
2182 method => "check_title_hold_batch",
2183 api_name => "open-ils.circ.title_hold.is_possible.batch",
2186 desc => '@see open-ils.circ.title_hold.is_possible.batch',
2188 { desc => 'Authentication token', type => 'string'},
2189 { desc => 'Array of Hash of named parameters', type => 'array'},
2192 desc => 'Array of response objects',
2198 sub check_title_hold_batch {
2199 my($self, $client, $authtoken, $param_list, $oargs) = @_;
2200 foreach (@$param_list) {
2201 my ($res) = $self->method_lookup('open-ils.circ.title_hold.is_possible')->run($authtoken, $_, $oargs);
2202 $client->respond($res);
2208 __PACKAGE__->register_method(
2209 method => "check_title_hold",
2210 api_name => "open-ils.circ.title_hold.is_possible",
2212 desc => 'Determines if a hold were to be placed by a given user, ' .
2213 'whether or not said hold would have any potential copies to fulfill it.' .
2214 'The named paramaters of the second argument include: ' .
2215 'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
2216 'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' ,
2218 { desc => 'Authentication token', type => 'string'},
2219 { desc => 'Hash of named parameters', type => 'object'},
2222 desc => 'List of new message IDs (empty if none)',
2228 =head3 check_title_hold (token, hash)
2230 The named fields in the hash are:
2232 patronid - ID of the hold recipient (required)
2233 depth - hold range depth (default 0)
2234 pickup_lib - destination for hold, fallback value for selection_ou
2235 selection_ou - ID of org_unit establishing hard and soft hold boundary settings
2236 issuanceid - ID of the issuance to be held, required for Issuance level hold
2237 partid - ID of the monograph part to be held, required for monograph part level hold
2238 titleid - ID (BRN) of the title to be held, required for Title level hold
2239 volume_id - required for Volume level hold
2240 copy_id - required for Copy level hold
2241 mrid - required for Meta-record level hold
2242 hold_type - T, C (or R or F), I, V or M for Title, Copy, Issuance, Volume or Meta-record (default "T")
2244 All key/value pairs are passed on to do_possibility_checks.
2248 # FIXME: better params checking. what other params are required, if any?
2249 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
2250 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still
2251 # used in conditionals, where it may be undefined, causing a warning.
2252 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
2254 sub check_title_hold {
2255 my( $self, $client, $authtoken, $params ) = @_;
2256 my $e = new_editor(authtoken=>$authtoken);
2257 return $e->event unless $e->checkauth;
2259 my %params = %$params;
2260 my $depth = $params{depth} || 0;
2261 my $selection_ou = $params{selection_ou} || $params{pickup_lib};
2262 my $oargs = $params{oargs} || {};
2264 if($oargs->{events}) {
2265 @{$oargs->{events}} = grep { $e->allowed($_ . '.override', $e->requestor->ws_ou); } @{$oargs->{events}};
2269 my $patron = $e->retrieve_actor_user($params{patronid})
2270 or return $e->event;
2272 if( $e->requestor->id ne $patron->id ) {
2273 return $e->event unless
2274 $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
2277 return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
2279 my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
2280 or return $e->event;
2282 my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
2283 my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
2286 my $return_depth = $hard_boundary; # default depth to return on success
2287 if(defined $soft_boundary and $depth < $soft_boundary) {
2288 # work up the tree and as soon as we find a potential copy, use that depth
2289 # also, make sure we don't go past the hard boundary if it exists
2291 # our min boundary is the greater of user-specified boundary or hard boundary
2292 my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?
2293 $hard_boundary : $depth;
2295 my $depth = $soft_boundary;
2296 while($depth >= $min_depth) {
2297 $logger->info("performing hold possibility check with soft boundary $depth");
2298 @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
2300 $return_depth = $depth;
2305 } elsif(defined $hard_boundary and $depth < $hard_boundary) {
2306 # there is no soft boundary, enforce the hard boundary if it exists
2307 $logger->info("performing hold possibility check with hard boundary $hard_boundary");
2308 @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
2310 # no boundaries defined, fall back to user specifed boundary or no boundary
2311 $logger->info("performing hold possibility check with no boundary");
2312 @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
2315 my $place_unfillable = 0;
2316 $place_unfillable = 1 if $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
2321 "depth" => $return_depth,
2322 "local_avail" => $status[1]
2324 } elsif ($status[2]) {
2325 my $n = scalar @{$status[2]};
2326 return {"success" => 0, "last_event" => $status[2]->[$n - 1], "age_protected_copy" => $status[3], "place_unfillable" => $place_unfillable};
2328 return {"success" => 0, "age_protected_copy" => $status[3], "place_unfillable" => $place_unfillable};
2334 sub do_possibility_checks {
2335 my($e, $patron, $request_lib, $depth, %params) = @_;
2337 my $issuanceid = $params{issuanceid} || "";
2338 my $partid = $params{partid} || "";
2339 my $titleid = $params{titleid} || "";
2340 my $volid = $params{volume_id};
2341 my $copyid = $params{copy_id};
2342 my $mrid = $params{mrid} || "";
2343 my $pickup_lib = $params{pickup_lib};
2344 my $hold_type = $params{hold_type} || 'T';
2345 my $selection_ou = $params{selection_ou} || $pickup_lib;
2346 my $holdable_formats = $params{holdable_formats};
2347 my $oargs = $params{oargs} || {};
2354 if( $hold_type eq OILS_HOLD_TYPE_FORCE || $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_COPY ) {
2356 return $e->event unless $copy = $e->retrieve_asset_copy($copyid);
2357 return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
2358 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2360 return (1, 1, []) if( $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_FORCE);
2361 return verify_copy_for_hold(
2362 $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib, $oargs
2365 } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2367 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
2368 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2370 return _check_volume_hold_is_possible(
2371 $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2374 } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
2376 return _check_title_hold_is_possible(
2377 $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, undef, $oargs
2380 } elsif( $hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2382 return _check_issuance_hold_is_possible(
2383 $issuanceid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2386 } elsif( $hold_type eq OILS_HOLD_TYPE_MONOPART ) {
2388 return _check_monopart_hold_is_possible(
2389 $partid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2392 } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2394 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
2395 my @recs = map { $_->source } @$maps;
2397 for my $rec (@recs) {
2398 @status = _check_title_hold_is_possible(
2399 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $holdable_formats, $oargs
2405 # else { Unrecognized hold_type ! } # FIXME: return error? or 0?
2409 sub create_ranged_org_filter {
2410 my($e, $selection_ou, $depth) = @_;
2412 # find the orgs from which this hold may be fulfilled,
2413 # based on the selection_ou and depth
2415 my $top_org = $e->search_actor_org_unit([
2416 {parent_ou => undef},
2417 {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
2420 return () if $depth == $top_org->ou_type->depth;
2422 my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
2423 %org_filter = (circ_lib => []);
2424 push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
2426 $logger->info("hold org filter at depth $depth and selection_ou ".
2427 "$selection_ou created list of @{$org_filter{circ_lib}}");
2433 sub _check_title_hold_is_possible {
2434 my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $holdable_formats, $oargs ) = @_;
2436 my ($types, $formats, $lang);
2437 if (defined($holdable_formats)) {
2438 ($types, $formats, $lang) = split '-', $holdable_formats;
2441 my $e = new_editor();
2442 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2444 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2445 my $copies = $e->json_query(
2447 select => { acp => ['id', 'circ_lib'] },
2452 fkey => 'call_number',
2456 filter => { id => $titleid },
2464 ( $types ? (item_type => [split '', $types]) : () ),
2465 ( $formats ? (item_form => [split '', $formats]) : () ),
2466 ( $lang ? (item_lang => $lang) : () )
2471 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2472 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' },
2473 acpm => { field => 'target_copy', type => 'left' } # ignore part-linked copies
2477 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter },
2478 '+acpm' => { target_copy => undef } # ignore part-linked copies
2483 $logger->info("title possible found ".scalar(@$copies)." potential copies");
2487 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2488 "payload" => {"fail_part" => "no_ultimate_items"}
2493 # -----------------------------------------------------------------------
2494 # sort the copies into buckets based on their circ_lib proximity to
2495 # the patron's home_ou.
2496 # -----------------------------------------------------------------------
2498 my $home_org = $patron->home_ou;
2499 my $req_org = $request_lib->id;
2501 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2503 $prox_cache{$home_org} =
2504 $e->search_actor_org_unit_proximity({from_org => $home_org})
2505 unless $prox_cache{$home_org};
2506 my $home_prox = $prox_cache{$home_org};
2509 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2510 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2512 my @keys = sort { $a <=> $b } keys %buckets;
2515 if( $home_org ne $req_org ) {
2516 # -----------------------------------------------------------------------
2517 # shove the copies close to the request_lib into the primary buckets
2518 # directly before the farthest away copies. That way, they are not
2519 # given priority, but they are checked before the farthest copies.
2520 # -----------------------------------------------------------------------
2521 $prox_cache{$req_org} =
2522 $e->search_actor_org_unit_proximity({from_org => $req_org})
2523 unless $prox_cache{$req_org};
2524 my $req_prox = $prox_cache{$req_org};
2527 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2528 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2530 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2531 my $new_key = $highest_key - 0.5; # right before the farthest prox
2532 my @keys2 = sort { $a <=> $b } keys %buckets2;
2533 for my $key (@keys2) {
2534 last if $key >= $highest_key;
2535 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2539 @keys = sort { $a <=> $b } keys %buckets;
2544 my $age_protect_only = 0;
2545 OUTER: for my $key (@keys) {
2546 my @cps = @{$buckets{$key}};
2548 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2550 for my $copyid (@cps) {
2552 next if $seen{$copyid};
2553 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2554 my $copy = $e->retrieve_asset_copy($copyid);
2555 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2557 unless($title) { # grab the title if we don't already have it
2558 my $vol = $e->retrieve_asset_call_number(
2559 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2560 $title = $vol->record;
2563 @status = verify_copy_for_hold(
2564 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2566 $age_protect_only ||= $status[3];
2567 last OUTER if $status[0];
2571 $status[3] = $age_protect_only;
2575 sub _check_issuance_hold_is_possible {
2576 my( $issuanceid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2578 my $e = new_editor();
2579 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2581 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2582 my $copies = $e->json_query(
2584 select => { acp => ['id', 'circ_lib'] },
2590 filter => { issuance => $issuanceid }
2592 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2593 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2597 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2603 $logger->info("issuance possible found ".scalar(@$copies)." potential copies");
2607 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2608 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2613 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2614 "payload" => {"fail_part" => "no_ultimate_items"}
2622 # -----------------------------------------------------------------------
2623 # sort the copies into buckets based on their circ_lib proximity to
2624 # the patron's home_ou.
2625 # -----------------------------------------------------------------------
2627 my $home_org = $patron->home_ou;
2628 my $req_org = $request_lib->id;
2630 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2632 $prox_cache{$home_org} =
2633 $e->search_actor_org_unit_proximity({from_org => $home_org})
2634 unless $prox_cache{$home_org};
2635 my $home_prox = $prox_cache{$home_org};
2638 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2639 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2641 my @keys = sort { $a <=> $b } keys %buckets;
2644 if( $home_org ne $req_org ) {
2645 # -----------------------------------------------------------------------
2646 # shove the copies close to the request_lib into the primary buckets
2647 # directly before the farthest away copies. That way, they are not
2648 # given priority, but they are checked before the farthest copies.
2649 # -----------------------------------------------------------------------
2650 $prox_cache{$req_org} =
2651 $e->search_actor_org_unit_proximity({from_org => $req_org})
2652 unless $prox_cache{$req_org};
2653 my $req_prox = $prox_cache{$req_org};
2656 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2657 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2659 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2660 my $new_key = $highest_key - 0.5; # right before the farthest prox
2661 my @keys2 = sort { $a <=> $b } keys %buckets2;
2662 for my $key (@keys2) {
2663 last if $key >= $highest_key;
2664 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2668 @keys = sort { $a <=> $b } keys %buckets;
2673 my $age_protect_only = 0;
2674 OUTER: for my $key (@keys) {
2675 my @cps = @{$buckets{$key}};
2677 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2679 for my $copyid (@cps) {
2681 next if $seen{$copyid};
2682 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2683 my $copy = $e->retrieve_asset_copy($copyid);
2684 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2686 unless($title) { # grab the title if we don't already have it
2687 my $vol = $e->retrieve_asset_call_number(
2688 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2689 $title = $vol->record;
2692 @status = verify_copy_for_hold(
2693 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2695 $age_protect_only ||= $status[3];
2696 last OUTER if $status[0];
2701 if (!defined($empty_ok)) {
2702 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2703 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2706 return (1,0) if ($empty_ok);
2708 $status[3] = $age_protect_only;
2712 sub _check_monopart_hold_is_possible {
2713 my( $partid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2715 my $e = new_editor();
2716 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2718 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2719 my $copies = $e->json_query(
2721 select => { acp => ['id', 'circ_lib'] },
2725 field => 'target_copy',
2727 filter => { part => $partid }
2729 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2730 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2734 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2740 $logger->info("monopart possible found ".scalar(@$copies)." potential copies");
2744 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2745 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2750 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2751 "payload" => {"fail_part" => "no_ultimate_items"}
2759 # -----------------------------------------------------------------------
2760 # sort the copies into buckets based on their circ_lib proximity to
2761 # the patron's home_ou.
2762 # -----------------------------------------------------------------------
2764 my $home_org = $patron->home_ou;
2765 my $req_org = $request_lib->id;
2767 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2769 $prox_cache{$home_org} =
2770 $e->search_actor_org_unit_proximity({from_org => $home_org})
2771 unless $prox_cache{$home_org};
2772 my $home_prox = $prox_cache{$home_org};
2775 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2776 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2778 my @keys = sort { $a <=> $b } keys %buckets;
2781 if( $home_org ne $req_org ) {
2782 # -----------------------------------------------------------------------
2783 # shove the copies close to the request_lib into the primary buckets
2784 # directly before the farthest away copies. That way, they are not
2785 # given priority, but they are checked before the farthest copies.
2786 # -----------------------------------------------------------------------
2787 $prox_cache{$req_org} =
2788 $e->search_actor_org_unit_proximity({from_org => $req_org})
2789 unless $prox_cache{$req_org};
2790 my $req_prox = $prox_cache{$req_org};
2793 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2794 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2796 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2797 my $new_key = $highest_key - 0.5; # right before the farthest prox
2798 my @keys2 = sort { $a <=> $b } keys %buckets2;
2799 for my $key (@keys2) {
2800 last if $key >= $highest_key;
2801 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2805 @keys = sort { $a <=> $b } keys %buckets;
2810 my $age_protect_only = 0;
2811 OUTER: for my $key (@keys) {
2812 my @cps = @{$buckets{$key}};
2814 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2816 for my $copyid (@cps) {
2818 next if $seen{$copyid};
2819 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2820 my $copy = $e->retrieve_asset_copy($copyid);
2821 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2823 unless($title) { # grab the title if we don't already have it
2824 my $vol = $e->retrieve_asset_call_number(
2825 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2826 $title = $vol->record;
2829 @status = verify_copy_for_hold(
2830 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2832 $age_protect_only ||= $status[3];
2833 last OUTER if $status[0];
2838 if (!defined($empty_ok)) {
2839 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2840 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2843 return (1,0) if ($empty_ok);
2845 $status[3] = $age_protect_only;
2850 sub _check_volume_hold_is_possible {
2851 my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2852 my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
2853 my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
2854 $logger->info("checking possibility of volume hold for volume ".$vol->id);
2856 my $filter_copies = [];
2857 for my $copy (@$copies) {
2858 # ignore part-mapped copies for regular volume level holds
2859 push(@$filter_copies, $copy) unless
2860 new_editor->search_asset_copy_part_map({target_copy => $copy->id})->[0];
2862 $copies = $filter_copies;
2867 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2868 "payload" => {"fail_part" => "no_ultimate_items"}
2874 my $age_protect_only = 0;
2875 for my $copy ( @$copies ) {
2876 @status = verify_copy_for_hold(
2877 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs );
2878 $age_protect_only ||= $status[3];
2881 $status[3] = $age_protect_only;
2887 sub verify_copy_for_hold {
2888 my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs ) = @_;
2889 # $oargs should be undef unless we're overriding.
2890 $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
2891 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2894 requestor => $requestor,
2897 title_descriptor => $title->fixed_fields,
2898 pickup_lib => $pickup_lib,
2899 request_lib => $request_lib,
2901 show_event_list => 1
2905 # Check for override permissions on events.
2906 if ($oargs && $permitted && scalar @$permitted) {
2907 # Remove the events from permitted that we can override.
2908 if ($oargs->{events}) {
2909 foreach my $evt (@{$oargs->{events}}) {
2910 $permitted = [grep {$_->{textcode} ne $evt} @{$permitted}];
2913 # Now, we handle the override all case by checking remaining
2914 # events against override permissions.
2915 if (scalar @$permitted && $oargs->{all}) {
2916 # Pre-set events and failed members of oargs to empty
2917 # arrays, if they are not set, yet.
2918 $oargs->{events} = [] unless ($oargs->{events});
2919 $oargs->{failed} = [] unless ($oargs->{failed});
2920 # When we're done with these checks, we swap permitted
2921 # with a reference to @disallowed.
2922 my @disallowed = ();
2923 foreach my $evt (@{$permitted}) {
2924 # Check if we've already seen the event in this
2925 # session and it failed.
2926 if (grep {$_ eq $evt->{textcode}} @{$oargs->{failed}}) {
2927 push(@disallowed, $evt);
2929 # We have to check if the requestor has the
2930 # override permission.
2932 # AppUtils::check_user_perms returns the perm if
2933 # the user doesn't have it, undef if they do.
2934 if ($apputils->check_user_perms($requestor->id, $requestor->ws_ou, $evt->{textcode} . '.override')) {
2935 push(@disallowed, $evt);
2936 push(@{$oargs->{failed}}, $evt->{textcode});
2938 push(@{$oargs->{events}}, $evt->{textcode});
2942 $permitted = \@disallowed;
2946 my $age_protect_only = 0;
2947 if (@$permitted == 1 && @$permitted[0]->{textcode} eq 'ITEM_AGE_PROTECTED') {
2948 $age_protect_only = 1;
2952 (not scalar @$permitted), # true if permitted is an empty arrayref
2953 ( # XXX This test is of very dubious value; someone should figure
2954 # out what if anything is checking this value
2955 ($copy->circ_lib == $pickup_lib) and
2956 ($copy->status == OILS_COPY_STATUS_AVAILABLE)
2965 sub find_nearest_permitted_hold {
2968 my $editor = shift; # CStoreEditor object
2969 my $copy = shift; # copy to target
2970 my $user = shift; # staff
2971 my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
2973 my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
2975 my $bc = $copy->barcode;
2977 # find any existing holds that already target this copy
2978 my $old_holds = $editor->search_action_hold_request(
2979 { current_copy => $copy->id,
2980 cancel_time => undef,
2981 capture_time => undef
2985 my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
2987 $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
2988 " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
2990 my $fifo = $U->ou_ancestor_setting_value($user->ws_ou, 'circ.holds_fifo');
2992 # search for what should be the best holds for this copy to fulfill
2993 my $best_holds = $U->storagereq(
2994 "open-ils.storage.action.hold_request.nearest_hold.atomic",
2995 $user->ws_ou, $copy->id, 100, $hold_stall_interval, $fifo );
2997 # Add any pre-targeted holds to the list too? Unless they are already there, anyway.
2999 for my $holdid (@$old_holds) {
3000 next unless $holdid;
3001 push(@$best_holds, $holdid) unless ( grep { ''.$holdid eq ''.$_ } @$best_holds );
3005 unless(@$best_holds) {
3006 $logger->info("circulator: no suitable holds found for copy $bc");
3007 return (undef, $evt);
3013 # for each potential hold, we have to run the permit script
3014 # to make sure the hold is actually permitted.
3017 for my $holdid (@$best_holds) {
3018 next unless $holdid;
3019 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
3021 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
3022 # Force and recall holds bypass all rules
3023 if ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
3027 my $reqr = $reqr_cache{$hold->requestor} || $editor->retrieve_actor_user($hold->requestor);
3028 my $rlib = $org_cache{$hold->request_lib} || $editor->retrieve_actor_org_unit($hold->request_lib);
3030 $reqr_cache{$hold->requestor} = $reqr;
3031 $org_cache{$hold->request_lib} = $rlib;
3033 # see if this hold is permitted
3034 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
3036 patron_id => $hold->usr,
3039 pickup_lib => $hold->pickup_lib,
3040 request_lib => $rlib,
3052 unless( $best_hold ) { # no "good" permitted holds were found
3054 $logger->info("circulator: no suitable holds found for copy $bc");
3055 return (undef, $evt);
3058 $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
3060 # indicate a permitted hold was found
3061 return $best_hold if $check_only;
3063 # we've found a permitted hold. we need to "grab" the copy
3064 # to prevent re-targeted holds (next part) from re-grabbing the copy
3065 $best_hold->current_copy($copy->id);
3066 $editor->update_action_hold_request($best_hold)
3067 or return (undef, $editor->event);
3072 # re-target any other holds that already target this copy
3073 for my $old_hold (@$old_holds) {
3074 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
3075 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
3076 $old_hold->id." after a better hold [".$best_hold->id."] was found");
3077 $old_hold->clear_current_copy;
3078 $old_hold->clear_prev_check_time;
3079 $editor->update_action_hold_request($old_hold)
3080 or return (undef, $editor->event);
3081 push(@retarget, $old_hold->id);
3084 return ($best_hold, undef, (@retarget) ? \@retarget : undef);
3092 __PACKAGE__->register_method(
3093 method => 'all_rec_holds',
3094 api_name => 'open-ils.circ.holds.retrieve_all_from_title',
3098 my( $self, $conn, $auth, $title_id, $args ) = @_;
3100 my $e = new_editor(authtoken=>$auth);
3101 $e->checkauth or return $e->event;
3102 $e->allowed('VIEW_HOLD') or return $e->event;
3105 $args->{fulfillment_time} = undef; # we don't want to see old fulfilled holds
3106 $args->{cancel_time} = undef;
3108 my $resp = { volume_holds => [], copy_holds => [], recall_holds => [], force_holds => [], metarecord_holds => [], part_holds => [], issuance_holds => [] };
3110 my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
3112 $resp->{metarecord_holds} = $e->search_action_hold_request(
3113 { hold_type => OILS_HOLD_TYPE_METARECORD,
3114 target => $mr_map->metarecord,
3120 $resp->{title_holds} = $e->search_action_hold_request(
3122 hold_type => OILS_HOLD_TYPE_TITLE,
3123 target => $title_id,
3127 my $parts = $e->search_biblio_monograph_part(
3133 $resp->{part_holds} = $e->search_action_hold_request(
3135 hold_type => OILS_HOLD_TYPE_MONOPART,
3141 my $subs = $e->search_serial_subscription(
3142 { record_entry => $title_id }, {idlist=>1});
3145 my $issuances = $e->search_serial_issuance(
3146 {subscription => $subs}, {idlist=>1}
3150 $resp->{issuance_holds} = $e->search_action_hold_request(
3152 hold_type => OILS_HOLD_TYPE_ISSUANCE,
3153 target => $issuances,
3160 my $vols = $e->search_asset_call_number(
3161 { record => $title_id, deleted => 'f' }, {idlist=>1});
3163 return $resp unless @$vols;
3165 $resp->{volume_holds} = $e->search_action_hold_request(
3167 hold_type => OILS_HOLD_TYPE_VOLUME,
3172 my $copies = $e->search_asset_copy(
3173 { call_number => $vols, deleted => 'f' }, {idlist=>1});
3175 return $resp unless @$copies;
3177 $resp->{copy_holds} = $e->search_action_hold_request(
3179 hold_type => OILS_HOLD_TYPE_COPY,
3184 $resp->{recall_holds} = $e->search_action_hold_request(
3186 hold_type => OILS_HOLD_TYPE_RECALL,
3191 $resp->{force_holds} = $e->search_action_hold_request(
3193 hold_type => OILS_HOLD_TYPE_FORCE,
3205 __PACKAGE__->register_method(
3206 method => 'uber_hold',
3208 api_name => 'open-ils.circ.hold.details.retrieve'
3212 my($self, $client, $auth, $hold_id, $args) = @_;
3213 my $e = new_editor(authtoken=>$auth);
3214 $e->checkauth or return $e->event;
3215 return uber_hold_impl($e, $hold_id, $args);
3218 __PACKAGE__->register_method(
3219 method => 'batch_uber_hold',
3222 api_name => 'open-ils.circ.hold.details.batch.retrieve'
3225 sub batch_uber_hold {
3226 my($self, $client, $auth, $hold_ids, $args) = @_;
3227 my $e = new_editor(authtoken=>$auth);
3228 $e->checkauth or return $e->event;
3229 $client->respond(uber_hold_impl($e, $_, $args)) for @$hold_ids;
3233 sub uber_hold_impl {
3234 my($e, $hold_id, $args) = @_;
3237 my $hold = $e->retrieve_action_hold_request(
3242 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
3245 ) or return $e->event;
3247 if($hold->usr->id ne $e->requestor->id) {
3248 # caller is asking for someone else's hold
3249 $e->allowed('VIEW_HOLD') or return $e->event;
3250 $hold->notes( # filter out any non-staff ("private") notes (unless marked as public)
3251 [ grep { $U->is_true($_->staff) or $U->is_true($_->pub) } @{$hold->notes} ] );
3254 # caller is asking for own hold, but may not have permission to view staff notes
3255 unless($e->allowed('VIEW_HOLD')) {
3256 $hold->notes( # filter out any staff notes (unless marked as public)
3257 [ grep { !$U->is_true($_->staff) or $U->is_true($_->pub) } @{$hold->notes} ] );
3261 my $user = $hold->usr;
3262 $hold->usr($user->id);
3265 my( $mvr, $volume, $copy, $issuance, $part, $bre ) = find_hold_mvr($e, $hold, $args->{suppress_mvr});
3267 flesh_hold_notices([$hold], $e) unless $args->{suppress_notices};
3268 flesh_hold_transits([$hold]) unless $args->{suppress_transits};
3270 my $details = retrieve_hold_queue_status_impl($e, $hold);
3275 ($copy ? (copy => $copy) : ()),
3276 ($volume ? (volume => $volume) : ()),
3277 ($issuance ? (issuance => $issuance) : ()),
3278 ($part ? (part => $part) : ()),
3279 ($args->{include_bre} ? (bre => $bre) : ()),
3280 ($args->{suppress_mvr} ? () : (mvr => $mvr)),
3284 unless($args->{suppress_patron_details}) {
3285 my $card = $e->retrieve_actor_card($user->card) or return $e->event;
3286 $resp->{patron_first} = $user->first_given_name,
3287 $resp->{patron_last} = $user->family_name,
3288 $resp->{patron_barcode} = $card->barcode,
3289 $resp->{patron_alias} = $user->alias,
3297 # -----------------------------------------------------
3298 # Returns the MVR object that represents what the
3300 # -----------------------------------------------------
3302 my( $e, $hold, $no_mvr ) = @_;
3310 if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
3311 my $mr = $e->retrieve_metabib_metarecord($hold->target)
3312 or return $e->event;
3313 $tid = $mr->master_record;
3315 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
3316 $tid = $hold->target;
3318 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
3319 $volume = $e->retrieve_asset_call_number($hold->target)
3320 or return $e->event;
3321 $tid = $volume->record;
3323 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
3324 $issuance = $e->retrieve_serial_issuance([
3326 {flesh => 1, flesh_fields => {siss => [ qw/subscription/ ]}}
3327 ]) or return $e->event;
3329 $tid = $issuance->subscription->record_entry;
3331 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_MONOPART ) {
3332 $part = $e->retrieve_biblio_monograph_part([
3334 ]) or return $e->event;
3336 $tid = $part->record;
3338 } 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 ) {
3339 $copy = $e->retrieve_asset_copy([
3341 {flesh => 1, flesh_fields => {acp => ['call_number']}}
3342 ]) or return $e->event;
3344 $volume = $copy->call_number;
3345 $tid = $volume->record;
3348 if(!$copy and ref $hold->current_copy ) {
3349 $copy = $hold->current_copy;
3350 $hold->current_copy($copy->id);
3353 if(!$volume and $copy) {
3354 $volume = $e->retrieve_asset_call_number($copy->call_number);
3357 # TODO return metarcord mvr for M holds
3358 my $title = $e->retrieve_biblio_record_entry($tid);
3359 return ( ($no_mvr) ? undef : $U->record_to_mvr($title), $volume, $copy, $issuance, $part, $title );
3362 __PACKAGE__->register_method(
3363 method => 'clear_shelf_cache',
3364 api_name => 'open-ils.circ.hold.clear_shelf.get_cache',
3368 Returns the holds processed with the given cache key
3373 sub clear_shelf_cache {
3374 my($self, $client, $auth, $cache_key, $chunk_size) = @_;
3375 my $e = new_editor(authtoken => $auth, xact => 1);
3376 return $e->die_event unless $e->checkauth and $e->allowed('VIEW_HOLD');
3379 my $hold_data = OpenSRF::Utils::Cache->new('global')->get_cache($cache_key);
3382 $logger->info("no hold data found in cache"); # XXX TODO return event
3388 foreach (keys %$hold_data) {
3389 $maximum += scalar(@{ $hold_data->{$_} });
3391 $client->respond({"maximum" => $maximum, "progress" => 0});
3393 for my $action (sort keys %$hold_data) {
3394 while (@{$hold_data->{$action}}) {
3395 my @hid_chunk = splice @{$hold_data->{$action}}, 0, $chunk_size;
3397 my $result_chunk = $e->json_query({
3399 "acp" => ["barcode"],
3401 first_given_name second_given_name family_name alias
3404 "acnp" => [{column => "label", alias => "prefix"}],
3405 "acns" => [{column => "label", alias => "suffix"}],
3413 "field" => "id", "fkey" => "current_copy",
3416 "field" => "id", "fkey" => "call_number",
3419 "field" => "id", "fkey" => "record"
3422 "field" => "id", "fkey" => "prefix"
3425 "field" => "id", "fkey" => "suffix"
3429 "acpl" => {"field" => "id", "fkey" => "location"}
3432 "au" => {"field" => "id", "fkey" => "usr"}
3435 "where" => {"+ahr" => {"id" => \@hid_chunk}}
3436 }, {"substream" => 1}) or return $e->die_event;
3440 +{"action" => $action, "hold_details" => $_}
3451 __PACKAGE__->register_method(
3452 method => 'clear_shelf_process',
3454 api_name => 'open-ils.circ.hold.clear_shelf.process',
3457 1. Find all holds that have expired on the holds shelf
3459 3. If a clear-shelf status is configured, put targeted copies into this status
3460 4. Divide copies into 3 groups: items to transit, items to reshelve, and items
3461 that are needed for holds. No subsequent action is taken on the holds
3462 or items after grouping.
3467 sub clear_shelf_process {
3468 my($self, $client, $auth, $org_id, $match_copy) = @_;
3470 my $e = new_editor(authtoken=>$auth);
3471 $e->checkauth or return $e->die_event;
3472 my $cache = OpenSRF::Utils::Cache->new('global');
3474 $org_id ||= $e->requestor->ws_ou;
3475 $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
3477 my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
3479 my @hold_ids = $self->method_lookup(
3480 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
3481 )->run($auth, $org_id, $match_copy);
3486 my @canceled_holds; # newly canceled holds
3487 my $chunk_size = 25; # chunked status updates
3489 for my $hold_id (@hold_ids) {
3491 $logger->info("Clear shelf processing hold $hold_id");
3493 my $hold = $e->retrieve_action_hold_request([
3496 flesh_fields => {ahr => ['current_copy']}
3500 if (!$hold->cancel_time) { # may be canceled but still on the holds shelf
3501 $hold->cancel_time('now');
3502 $hold->cancel_cause(2); # Hold Shelf expiration
3503 $e->update_action_hold_request($hold) or return $e->die_event;
3504 delete_hold_copy_maps($self, $e, $hold->id) and return $e->die_event;
3505 push(@canceled_holds, $hold_id);
3508 my $copy = $hold->current_copy;
3510 if($copy_status or $copy_status == 0) {
3511 # if a clear-shelf copy status is defined, update the copy
3512 $copy->status($copy_status);
3513 $copy->edit_date('now');
3514 $copy->editor($e->requestor->id);
3515 $e->update_asset_copy($copy) or return $e->die_event;
3518 push(@holds, $hold);
3519 $client->respond({maximum => scalar(@holds), progress => $counter}) if ( (++$counter % $chunk_size) == 0);
3530 for my $hold (@holds) {
3532 my $copy = $hold->current_copy;
3533 my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
3535 if($alt_hold and !$match_copy) {
3537 push(@{$cache_data{hold}}, $hold->id); # copy is needed for a hold
3539 } elsif($copy->circ_lib != $e->requestor->ws_ou) {
3541 push(@{$cache_data{transit}}, $hold->id); # copy needs to transit
3545 push(@{$cache_data{shelf}}, $hold->id); # copy needs to go back to the shelf
3549 my $cache_key = md5_hex(time . $$ . rand());
3550 $logger->info("clear_shelf_cache: storing under $cache_key");
3551 $cache->put_cache($cache_key, \%cache_data, 7200); # TODO: 2 hours. configurable?
3553 # tell the client we're done
3554 $client->respond_complete({cache_key => $cache_key});
3557 # fire off the hold cancelation trigger and wait for response so don't flood the service
3559 # refetch the holds to pick up the caclulated cancel_time,
3560 # which may be needed by Action/Trigger
3562 my $updated_holds = [];
3563 $updated_holds = $e->search_action_hold_request({id => \@canceled_holds}, {substream => 1}) if (@canceled_holds > 0);
3566 $U->create_events_for_hook(
3567 'hold_request.cancel.expire_holds_shelf',
3568 $_, $org_id, undef, undef, 1) for @$updated_holds;
3571 # tell the client we're done
3572 $client->respond_complete;
3576 __PACKAGE__->register_method(
3577 method => 'usr_hold_summary',
3578 api_name => 'open-ils.circ.holds.user_summary',
3580 Returns a summary of holds statuses for a given user
3584 sub usr_hold_summary {
3585 my($self, $conn, $auth, $user_id) = @_;
3587 my $e = new_editor(authtoken=>$auth);
3588 $e->checkauth or return $e->event;
3589 $e->allowed('VIEW_HOLD') or return $e->event;
3591 my $holds = $e->search_action_hold_request(
3594 fulfillment_time => undef,
3595 cancel_time => undef,
3599 my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
3600 $summary{_hold_status($e, $_)} += 1 for @$holds;
3606 __PACKAGE__->register_method(
3607 method => 'hold_has_copy_at',
3608 api_name => 'open-ils.circ.hold.has_copy_at',
3611 'Returns the ID of the found copy and name of the shelving location if there is ' .
3612 'an available copy at the specified org unit. Returns empty hash otherwise. ' .
3613 'The anticipated use for this method is to determine whether an item is ' .
3614 'available at the library where the user is placing the hold (or, alternatively, '.
3615 'at the pickup library) to encourage bypassing the hold placement and just ' .
3616 'checking out the item.' ,
3618 { desc => 'Authentication Token', type => 'string' },
3619 { desc => 'Method Arguments. Options include: hold_type, hold_target, org_unit. '
3620 . 'hold_type is the hold type code (T, V, C, M, ...). '
3621 . 'hold_target is the identifier of the hold target object. '
3622 . 'org_unit is org unit ID.',
3627 desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
3633 sub hold_has_copy_at {
3634 my($self, $conn, $auth, $args) = @_;
3636 my $e = new_editor(authtoken=>$auth);
3637 $e->checkauth or return $e->event;
3639 my $hold_type = $$args{hold_type};
3640 my $hold_target = $$args{hold_target};
3641 my $org_unit = $$args{org_unit};
3644 select => {acp => ['id'], acpl => ['name']},
3647 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
3648 ccs => {field => 'id', filter => { holdable => 't'}, fkey => 'status' }
3651 where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit, status => [0,7]}},
3655 if($hold_type eq 'C' or $hold_type eq 'F' or $hold_type eq 'R') {
3657 $query->{where}->{'+acp'}->{id} = $hold_target;
3659 } elsif($hold_type eq 'V') {
3661 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3663 } elsif($hold_type eq 'P') {
3665 $query->{from}->{acp}->{acpm} = {
3666 field => 'target_copy',
3668 filter => {part => $hold_target},
3671 } elsif($hold_type eq 'I') {
3673 $query->{from}->{acp}->{sitem} = {
3676 filter => {issuance => $hold_target},
3679 } elsif($hold_type eq 'T') {
3681 $query->{from}->{acp}->{acn} = {
3683 fkey => 'call_number',
3687 filter => {id => $hold_target},
3695 $query->{from}->{acp}->{acn} = {
3697 fkey => 'call_number',
3706 filter => {metarecord => $hold_target},
3714 my $res = $e->json_query($query)->[0] or return {};
3715 return {copy => $res->{id}, location => $res->{name}} if $res;
3719 # returns true if the user already has an item checked out
3720 # that could be used to fulfill the requested hold.
3721 sub hold_item_is_checked_out {
3722 my($e, $user_id, $hold_type, $hold_target) = @_;
3725 select => {acp => ['id']},
3726 from => {acp => {}},
3730 in => { # copies for circs the user has checked out
3731 select => {circ => ['target_copy']},
3735 checkin_time => undef,
3737 {stop_fines => ["MAXFINES","LONGOVERDUE"]},
3738 {stop_fines => undef}
3748 if($hold_type eq 'C' || $hold_type eq 'R' || $hold_type eq 'F') {
3750 $query->{where}->{'+acp'}->{id}->{in}->{where}->{'target_copy'} = $hold_target;
3752 } elsif($hold_type eq 'V') {
3754 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3756 } elsif($hold_type eq 'P') {
3758 $query->{from}->{acp}->{acpm} = {
3759 field => 'target_copy',
3761 filter => {part => $hold_target},
3764 } elsif($hold_type eq 'I') {
3766 $query->{from}->{acp}->{sitem} = {
3769 filter => {issuance => $hold_target},
3772 } elsif($hold_type eq 'T') {
3774 $query->{from}->{acp}->{acn} = {
3776 fkey => 'call_number',
3780 filter => {id => $hold_target},
3788 $query->{from}->{acp}->{acn} = {
3790 fkey => 'call_number',
3799 filter => {metarecord => $hold_target},
3807 return $e->json_query($query)->[0];
3810 __PACKAGE__->register_method(
3811 method => 'change_hold_title',
3812 api_name => 'open-ils.circ.hold.change_title',
3815 Updates all title level holds targeting the specified bibs to point a new bib./,
3817 { desc => 'Authentication Token', type => 'string' },
3818 { desc => 'New Target Bib Id', type => 'number' },
3819 { desc => 'Old Target Bib Ids', type => 'array' },
3821 return => { desc => '1 on success' }
3825 __PACKAGE__->register_method(
3826 method => 'change_hold_title_for_specific_holds',
3827 api_name => 'open-ils.circ.hold.change_title.specific_holds',
3830 Updates specified holds to target new bib./,
3832 { desc => 'Authentication Token', type => 'string' },
3833 { desc => 'New Target Bib Id', type => 'number' },
3834 { desc => 'Holds Ids for holds to update', type => 'array' },
3836 return => { desc => '1 on success' }
3841 sub change_hold_title {
3842 my( $self, $client, $auth, $new_bib_id, $bib_ids ) = @_;
3844 my $e = new_editor(authtoken=>$auth, xact=>1);
3845 return $e->die_event unless $e->checkauth;
3847 my $holds = $e->search_action_hold_request(
3850 cancel_time => undef,
3851 fulfillment_time => undef,
3857 flesh_fields => { ahr => ['usr'] }
3863 for my $hold (@$holds) {
3864 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3865 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3866 $hold->target( $new_bib_id );
3867 $e->update_action_hold_request($hold) or return $e->die_event;
3872 _reset_hold($self, $e->requestor, $_) for @$holds;
3877 sub change_hold_title_for_specific_holds {
3878 my( $self, $client, $auth, $new_bib_id, $hold_ids ) = @_;
3880 my $e = new_editor(authtoken=>$auth, xact=>1);
3881 return $e->die_event unless $e->checkauth;
3883 my $holds = $e->search_action_hold_request(
3886 cancel_time => undef,
3887 fulfillment_time => undef,
3893 flesh_fields => { ahr => ['usr'] }
3899 for my $hold (@$holds) {
3900 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3901 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3902 $hold->target( $new_bib_id );
3903 $e->update_action_hold_request($hold) or return $e->die_event;
3908 _reset_hold($self, $e->requestor, $_) for @$holds;
3913 __PACKAGE__->register_method(
3914 method => 'rec_hold_count',
3915 api_name => 'open-ils.circ.bre.holds.count',
3917 desc => q/Returns the total number of holds that target the
3918 selected bib record or its associated copies and call_numbers/,
3920 { desc => 'Bib ID', type => 'number' },
3922 return => {desc => 'Hold count', type => 'number'}
3926 __PACKAGE__->register_method(
3927 method => 'rec_hold_count',
3928 api_name => 'open-ils.circ.mmr.holds.count',
3930 desc => q/Returns the total number of holds that target the
3931 selected metarecord or its associated copies, call_numbers, and bib records/,
3933 { desc => 'Metarecord ID', type => 'number' },
3935 return => {desc => 'Hold count', type => 'number'}
3939 # XXX Need to add type I (and, soon, type P) holds to these counts
3940 sub rec_hold_count {
3941 my($self, $conn, $target_id) = @_;
3948 filter => {metarecord => $target_id}
3955 filter => { id => $target_id },
3960 if($self->api_name =~ /mmr/) {
3961 delete $bre_join->{bre}->{filter};
3962 $bre_join->{bre}->{join} = $mmr_join;
3968 fkey => 'call_number',
3974 select => {ahr => [{column => 'id', transform => 'count', alias => 'count'}]},
3978 cancel_time => undef,
3979 fulfillment_time => undef,
3983 hold_type => [qw/C F R/],
3986 select => {acp => ['id']},
3987 from => { acp => $cn_join }
3997 select => {acn => ['id']},
3998 from => {acn => $bre_join}
4006 target => $target_id
4014 if($self->api_name =~ /mmr/) {
4015 $query->{where}->{'+ahr'}->{'-or'}->[2] = {
4020 select => {bre => ['id']},
4021 from => {bre => $mmr_join}
4027 $query->{where}->{'+ahr'}->{'-or'}->[3] = {
4030 target => $target_id
4036 return new_editor()->json_query($query)->[0]->{count};