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";
43 __PACKAGE__->register_method(
44 method => "create_hold_batch",
45 api_name => "open-ils.circ.holds.create.batch",
48 desc => q/@see open-ils.circ.holds.create.batch/,
50 { desc => 'Authentication token', type => 'string' },
51 { desc => 'Array of hold objects', 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 => "create_hold_batch",
61 api_name => "open-ils.circ.holds.create.override.batch",
64 desc => '@see open-ils.circ.holds.create.batch',
69 sub create_hold_batch {
70 my( $self, $conn, $auth, $hold_list ) = @_;
71 (my $method = $self->api_name) =~ s/\.batch//og;
72 foreach (@$hold_list) {
73 my ($res) = $self->method_lookup($method)->run($auth, $_);
80 __PACKAGE__->register_method(
81 method => "create_hold",
82 api_name => "open-ils.circ.holds.create",
84 desc => "Create a new hold for an item. From a permissions perspective, " .
85 "the login session is used as the 'requestor' of the hold. " .
86 "The hold recipient is determined by the 'usr' setting within the hold object. " .
87 'First we verify the requestor has holds request permissions. ' .
88 'Then we verify that the recipient is allowed to make the given hold. ' .
89 'If not, we see if the requestor has "override" capabilities. If not, ' .
90 'a permission exception is returned. If permissions allow, we cycle ' .
91 'through the set of holds objects and create. ' .
92 'If the recipient does not have permission to place multiple holds ' .
93 'on a single title and said operation is attempted, a permission ' .
94 'exception is returned',
96 { desc => 'Authentication token', type => 'string' },
97 { desc => 'Hold object for hold to be created',
98 type => 'object', class => 'ahr' }
101 desc => 'New ahr ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
106 __PACKAGE__->register_method(
107 method => "create_hold",
108 api_name => "open-ils.circ.holds.create.override",
109 notes => '@see open-ils.circ.holds.create',
111 desc => "If the recipient is not allowed to receive the requested hold, " .
112 "call this method to attempt the override",
114 { desc => 'Authentication token', type => 'string' },
116 desc => 'Hold object for hold to be created',
117 type => 'object', class => 'ahr'
121 desc => 'New hold (ahr) ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
127 my( $self, $conn, $auth, $hold ) = @_;
128 return -1 unless $hold;
129 my $e = new_editor(authtoken=>$auth, xact=>1);
130 return $e->die_event unless $e->checkauth;
132 my $override = 1 if $self->api_name =~ /override/;
136 my $requestor = $e->requestor;
137 my $recipient = $requestor;
139 if( $requestor->id ne $hold->usr ) {
140 # Make sure the requestor is allowed to place holds for
141 # the recipient if they are not the same people
142 $recipient = $e->retrieve_actor_user($hold->usr) or return $e->die_event;
143 $e->allowed('REQUEST_HOLDS', $recipient->home_ou) or return $e->die_event;
146 # If the related org setting tells us to, block if patron privs have expired
147 my $expire_setting = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_BLOCK_HOLD_FOR_EXPIRED_PATRON);
148 if ($expire_setting) {
149 my $expire = DateTime::Format::ISO8601->new->parse_datetime(
150 cleanse_ISO8601($recipient->expire_date));
152 push( @events, OpenILS::Event->new(
153 'PATRON_ACCOUNT_EXPIRED',
154 "payload" => {"fail_part" => "actor.usr.privs_expired"}
155 )) if( CORE::time > $expire->epoch ) ;
158 # Now make sure the recipient is allowed to receive the specified hold
159 my $porg = $recipient->home_ou;
160 my $rid = $e->requestor->id;
161 my $t = $hold->hold_type;
163 # See if a duplicate hold already exists
165 usr => $recipient->id,
167 fulfillment_time => undef,
168 target => $hold->target,
169 cancel_time => undef,
172 $sargs->{holdable_formats} = $hold->holdable_formats if $t eq 'M';
174 my $existing = $e->search_action_hold_request($sargs);
175 push( @events, OpenILS::Event->new('HOLD_EXISTS')) if @$existing;
177 my $checked_out = hold_item_is_checked_out($e, $recipient->id, $hold->hold_type, $hold->target);
178 push( @events, OpenILS::Event->new('HOLD_ITEM_CHECKED_OUT')) if $checked_out;
180 if ( $t eq OILS_HOLD_TYPE_METARECORD ) {
181 return $e->die_event unless $e->allowed('MR_HOLDS', $porg);
182 } elsif ( $t eq OILS_HOLD_TYPE_TITLE ) {
183 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
184 } elsif ( $t eq OILS_HOLD_TYPE_VOLUME ) {
185 return $e->die_event unless $e->allowed('VOLUME_HOLDS', $porg);
186 } elsif ( $t eq OILS_HOLD_TYPE_ISSUANCE ) {
187 return $e->die_event unless $e->allowed('ISSUANCE_HOLDS', $porg);
188 } elsif ( $t eq OILS_HOLD_TYPE_COPY ) {
189 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
190 } elsif ( $t eq OILS_HOLD_TYPE_FORCE ) {
191 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
192 } elsif ( $t eq OILS_HOLD_TYPE_RECALL ) {
193 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
201 for my $evt (@events) {
203 my $name = $evt->{textcode};
204 return $e->die_event unless $e->allowed("$name.override", $porg);
208 # set the configured expire time
209 unless($hold->expire_time) {
210 my $interval = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_HOLD_EXPIRE);
212 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
213 $hold->expire_time($U->epoch2ISO8601($date->epoch));
217 $hold->requestor($e->requestor->id);
218 $hold->request_lib($e->requestor->ws_ou);
219 $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
220 $hold = $e->create_action_hold_request($hold) or return $e->die_event;
224 $conn->respond_complete($hold->id);
227 'open-ils.storage.action.hold_request.copy_targeter',
228 undef, $hold->id ) unless $U->is_true($hold->frozen);
233 # makes sure that a user has permission to place the type of requested hold
234 # returns the Perm exception if not allowed, returns undef if all is well
235 sub _check_holds_perm {
236 my($type, $user_id, $org_id) = @_;
240 $evt = $apputils->check_perms($user_id, $org_id, "MR_HOLDS" );
241 } elsif ($type eq "T") {
242 $evt = $apputils->check_perms($user_id, $org_id, "TITLE_HOLDS" );
243 } elsif($type eq "V") {
244 $evt = $apputils->check_perms($user_id, $org_id, "VOLUME_HOLDS");
245 } elsif($type eq "C") {
246 $evt = $apputils->check_perms($user_id, $org_id, "COPY_HOLDS" );
253 # tests if the given user is allowed to place holds on another's behalf
254 sub _check_request_holds_perm {
257 if (my $evt = $apputils->check_perms(
258 $user_id, $org_id, "REQUEST_HOLDS")) {
263 my $ses_is_req_note = 'The login session is the requestor. If the requestor is different from the user, ' .
264 'then the requestor must have VIEW_HOLD permissions';
266 __PACKAGE__->register_method(
267 method => "retrieve_holds_by_id",
268 api_name => "open-ils.circ.holds.retrieve_by_id",
270 desc => "Retrieve the hold, with hold transits attached, for the specified ID. $ses_is_req_note",
272 { desc => 'Authentication token', type => 'string' },
273 { desc => 'Hold ID', type => 'number' }
276 desc => 'Hold object with transits attached, event on error',
282 sub retrieve_holds_by_id {
283 my($self, $client, $auth, $hold_id) = @_;
284 my $e = new_editor(authtoken=>$auth);
285 $e->checkauth or return $e->event;
286 $e->allowed('VIEW_HOLD') or return $e->event;
288 my $holds = $e->search_action_hold_request(
290 { id => $hold_id , fulfillment_time => undef },
292 order_by => { ahr => "request_time" },
294 flesh_fields => {ahr => ['notes']}
299 flesh_hold_transits($holds);
300 flesh_hold_notices($holds, $e);
305 __PACKAGE__->register_method(
306 method => "retrieve_holds",
307 api_name => "open-ils.circ.holds.retrieve",
309 desc => "Retrieves all the holds, with hold transits attached, for the specified user. $ses_is_req_note",
311 { desc => 'Authentication token', type => 'string' },
312 { desc => 'User ID', type => 'integer' }
315 desc => 'list of holds, event on error',
320 __PACKAGE__->register_method(
321 method => "retrieve_holds",
322 api_name => "open-ils.circ.holds.id_list.retrieve",
325 desc => "Retrieves all the hold IDs, for the specified user. $ses_is_req_note",
327 { desc => 'Authentication token', type => 'string' },
328 { desc => 'User ID', type => 'integer' }
331 desc => 'list of holds, event on error',
336 __PACKAGE__->register_method(
337 method => "retrieve_holds",
338 api_name => "open-ils.circ.holds.canceled.retrieve",
341 desc => "Retrieves all the cancelled holds for the specified user. $ses_is_req_note",
343 { desc => 'Authentication token', type => 'string' },
344 { desc => 'User ID', type => 'integer' }
347 desc => 'list of holds, event on error',
352 __PACKAGE__->register_method(
353 method => "retrieve_holds",
354 api_name => "open-ils.circ.holds.canceled.id_list.retrieve",
357 desc => "Retrieves list of cancelled hold IDs for the specified user. $ses_is_req_note",
359 { desc => 'Authentication token', type => 'string' },
360 { desc => 'User ID', type => 'integer' }
363 desc => 'list of hold IDs, event on error',
370 my ($self, $client, $auth, $user_id) = @_;
372 my $e = new_editor(authtoken=>$auth);
373 return $e->event unless $e->checkauth;
374 $user_id = $e->requestor->id unless defined $user_id;
376 my $notes_filter = {staff => 'f'};
377 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
378 unless($user_id == $e->requestor->id) {
379 if($e->allowed('VIEW_HOLD', $user->home_ou)) {
380 $notes_filter = {staff => 't'}
382 my $allowed = OpenILS::Application::Actor::Friends->friend_perm_allowed(
383 $e, $user_id, $e->requestor->id, 'hold.view');
384 return $e->event unless $allowed;
387 # staff member looking at his/her own holds can see staff and non-staff notes
388 $notes_filter = {} if $e->allowed('VIEW_HOLD', $user->home_ou);
392 select => {ahr => ['id']},
394 where => {usr => $user_id, fulfillment_time => undef}
397 if($self->api_name =~ /canceled/) {
399 # Fetch the canceled holds
400 # order cancelled holds by cancel time, most recent first
402 $holds_query->{order_by} = [{class => 'ahr', field => 'cancel_time', direction => 'desc'}];
405 my $cancel_count = $U->ou_ancestor_setting_value(
406 $e->requestor->ws_ou, 'circ.holds.canceled.display_count', $e);
408 unless($cancel_count) {
409 $cancel_age = $U->ou_ancestor_setting_value(
410 $e->requestor->ws_ou, 'circ.holds.canceled.display_age', $e);
412 # if no settings are defined, default to last 10 cancelled holds
413 $cancel_count = 10 unless $cancel_age;
416 if($cancel_count) { # limit by count
418 $holds_query->{where}->{cancel_time} = {'!=' => undef};
419 $holds_query->{limit} = $cancel_count;
421 } elsif($cancel_age) { # limit by age
423 # find all of the canceled holds that were canceled within the configured time frame
424 my $date = DateTime->now->subtract(seconds => OpenSRF::Utils::interval_to_seconds($cancel_age));
425 $date = $U->epoch2ISO8601($date->epoch);
426 $holds_query->{where}->{cancel_time} = {'>=' => $date};
431 # order non-cancelled holds by ready-for-pickup, then active, followed by suspended
432 $holds_query->{order_by} = {ahr => ['shelf_time', 'frozen', 'request_time']};
433 $holds_query->{where}->{cancel_time} = undef;
436 my $hold_ids = $e->json_query($holds_query);
437 $hold_ids = [ map { $_->{id} } @$hold_ids ];
439 return $hold_ids if $self->api_name =~ /id_list/;
442 for my $hold_id ( @$hold_ids ) {
444 my $hold = $e->retrieve_action_hold_request($hold_id);
445 $hold->notes($e->search_action_hold_request_note({hold => $hold_id, %$notes_filter}));
448 $e->search_action_hold_transit_copy([
450 {order_by => {ahtc => 'source_send_time desc'}, limit => 1}])->[0]
460 __PACKAGE__->register_method(
461 method => 'user_hold_count',
462 api_name => 'open-ils.circ.hold.user.count'
465 sub user_hold_count {
466 my ( $self, $conn, $auth, $userid ) = @_;
467 my $e = new_editor( authtoken => $auth );
468 return $e->event unless $e->checkauth;
469 my $patron = $e->retrieve_actor_user($userid)
471 return $e->event unless $e->allowed( 'VIEW_HOLD', $patron->home_ou );
472 return __user_hold_count( $self, $e, $userid );
475 sub __user_hold_count {
476 my ( $self, $e, $userid ) = @_;
477 my $holds = $e->search_action_hold_request(
480 fulfillment_time => undef,
481 cancel_time => undef,
486 return scalar(@$holds);
490 __PACKAGE__->register_method(
491 method => "retrieve_holds_by_pickup_lib",
492 api_name => "open-ils.circ.holds.retrieve_by_pickup_lib",
494 "Retrieves all the holds, with hold transits attached, for the specified pickup_ou id."
497 __PACKAGE__->register_method(
498 method => "retrieve_holds_by_pickup_lib",
499 api_name => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
500 notes => "Retrieves all the hold ids for the specified pickup_ou id. "
503 sub retrieve_holds_by_pickup_lib {
504 my ($self, $client, $login_session, $ou_id) = @_;
506 #FIXME -- put an appropriate permission check here
507 #my( $user, $target, $evt ) = $apputils->checkses_requestor(
508 # $login_session, $user_id, 'VIEW_HOLD' );
509 #return $evt if $evt;
511 my $holds = $apputils->simplereq(
513 "open-ils.cstore.direct.action.hold_request.search.atomic",
515 pickup_lib => $ou_id ,
516 fulfillment_time => undef,
519 { order_by => { ahr => "request_time" } }
522 if ( ! $self->api_name =~ /id_list/ ) {
523 flesh_hold_transits($holds);
527 return [ map { $_->id } @$holds ];
531 __PACKAGE__->register_method(
532 method => "uncancel_hold",
533 api_name => "open-ils.circ.hold.uncancel"
537 my($self, $client, $auth, $hold_id) = @_;
538 my $e = new_editor(authtoken=>$auth, xact=>1);
539 return $e->die_event unless $e->checkauth;
541 my $hold = $e->retrieve_action_hold_request($hold_id)
542 or return $e->die_event;
543 return $e->die_event unless $e->allowed('CANCEL_HOLDS', $hold->request_lib);
545 if ($hold->fulfillment_time) {
549 unless ($hold->cancel_time) {
554 # if configured to reset the request time, also reset the expire time
555 if($U->ou_ancestor_setting_value(
556 $hold->request_lib, 'circ.holds.uncancel.reset_request_time', $e)) {
558 $hold->request_time('now');
559 my $interval = $U->ou_ancestor_setting_value($hold->request_lib, OILS_SETTING_HOLD_EXPIRE);
561 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
562 $hold->expire_time($U->epoch2ISO8601($date->epoch));
566 $hold->clear_cancel_time;
567 $hold->clear_cancel_cause;
568 $hold->clear_cancel_note;
569 $hold->clear_shelf_time;
570 $hold->clear_current_copy;
571 $hold->clear_capture_time;
572 $hold->clear_prev_check_time;
573 $hold->clear_shelf_expire_time;
575 $e->update_action_hold_request($hold) or return $e->die_event;
578 $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
584 __PACKAGE__->register_method(
585 method => "cancel_hold",
586 api_name => "open-ils.circ.hold.cancel",
588 desc => 'Cancels the specified hold. The login session is the requestor. If the requestor is different from the usr field ' .
589 'on the hold, the requestor must have CANCEL_HOLDS permissions. The hold may be either the hold object or the hold id',
591 {desc => 'Authentication token', type => 'string'},
592 {desc => 'Hold ID', type => 'number'},
593 {desc => 'Cause of Cancellation', type => 'string'},
594 {desc => 'Note', type => 'string'}
597 desc => '1 on success, event on error'
603 my($self, $client, $auth, $holdid, $cause, $note) = @_;
605 my $e = new_editor(authtoken=>$auth, xact=>1);
606 return $e->die_event unless $e->checkauth;
608 my $hold = $e->retrieve_action_hold_request($holdid)
609 or return $e->die_event;
611 if( $e->requestor->id ne $hold->usr ) {
612 return $e->die_event unless $e->allowed('CANCEL_HOLDS');
615 if ($hold->cancel_time) {
620 # If the hold is captured, reset the copy status
621 if( $hold->capture_time and $hold->current_copy ) {
623 my $copy = $e->retrieve_asset_copy($hold->current_copy)
624 or return $e->die_event;
626 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
627 $logger->info("canceling hold $holdid whose item is on the holds shelf");
628 # $logger->info("setting copy to status 'reshelving' on hold cancel");
629 # $copy->status(OILS_COPY_STATUS_RESHELVING);
630 # $copy->editor($e->requestor->id);
631 # $copy->edit_date('now');
632 # $e->update_asset_copy($copy) or return $e->event;
634 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
637 $logger->warn("! canceling hold [$hid] that is in transit");
638 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
641 my $trans = $e->retrieve_action_transit_copy($transid);
642 # Leave the transit alive, but set the copy status to
643 # reshelving so it will be properly reshelved when it gets back home
645 $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
646 $e->update_action_transit_copy($trans) or return $e->die_event;
652 $hold->cancel_time('now');
653 $hold->cancel_cause($cause);
654 $hold->cancel_note($note);
655 $e->update_action_hold_request($hold)
656 or return $e->die_event;
658 delete_hold_copy_maps($self, $e, $hold->id);
662 $U->create_events_for_hook('hold_request.cancel.staff', $hold, $hold->pickup_lib)
663 if $e->requestor->id != $hold->usr;
668 sub delete_hold_copy_maps {
673 my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
675 $editor->delete_action_hold_copy_map($_)
676 or return $editor->event;
682 my $update_hold_desc = 'The login session is the requestor. ' .
683 'If the requestor is different from the usr field on the hold, ' .
684 'the requestor must have UPDATE_HOLDS permissions. ' .
685 'If supplying a hash of hold data, "id" must be included. ' .
686 'The hash is ignored if a hold object is supplied, ' .
687 'so you should supply only one kind of hold data argument.' ;
689 __PACKAGE__->register_method(
690 method => "update_hold",
691 api_name => "open-ils.circ.hold.update",
693 desc => "Updates the specified hold. $update_hold_desc",
695 {desc => 'Authentication token', type => 'string'},
696 {desc => 'Hold Object', type => 'object'},
697 {desc => 'Hash of values to be applied', type => 'object'}
700 desc => 'Hold ID on success, event on error',
706 __PACKAGE__->register_method(
707 method => "batch_update_hold",
708 api_name => "open-ils.circ.hold.update.batch",
711 desc => "Updates the specified hold(s). $update_hold_desc",
713 {desc => 'Authentication token', type => 'string'},
714 {desc => 'Array of hold obejcts', type => 'array' },
715 {desc => 'Array of hashes of values to be applied', type => 'array' }
718 desc => 'Hold ID per success, event per error',
724 my($self, $client, $auth, $hold, $values) = @_;
725 my $e = new_editor(authtoken=>$auth, xact=>1);
726 return $e->die_event unless $e->checkauth;
727 my $resp = update_hold_impl($self, $e, $hold, $values);
728 if ($U->event_code($resp)) {
732 $e->commit; # FIXME: update_hold_impl already does $e->commit ??
736 sub batch_update_hold {
737 my($self, $client, $auth, $hold_list, $values_list) = @_;
738 my $e = new_editor(authtoken=>$auth);
739 return $e->die_event unless $e->checkauth;
741 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.
743 $values_list ||= []; # FIXME: either move this above $count declaration, or send an event if both lists undef. Probably the latter.
745 # FIXME: Failing over to [] guarantees warnings for "Use of unitialized value" in update_hold_impl call.
746 # FIXME: We should be sure we only call update_hold_impl with hold object OR hash, not both.
748 for my $idx (0..$count-1) {
750 my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
751 $e->xact_commit unless $U->event_code($resp);
752 $client->respond($resp);
756 return undef; # not in the register return type, assuming we should always have at least one list populated
759 sub update_hold_impl {
760 my($self, $e, $hold, $values) = @_;
763 $hold = $e->retrieve_action_hold_request($values->{id})
764 or return $e->die_event;
765 for my $k (keys %$values) {
766 if (defined $values->{$k}) {
767 $hold->$k($values->{$k});
769 my $f = "clear_$k"; $hold->$f();
774 my $orig_hold = $e->retrieve_action_hold_request($hold->id)
775 or return $e->die_event;
777 # don't allow the user to be changed
778 return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
780 if($hold->usr ne $e->requestor->id) {
781 # if the hold is for a different user, make sure the
782 # requestor has the appropriate permissions
783 my $usr = $e->retrieve_actor_user($hold->usr)
784 or return $e->die_event;
785 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
789 # --------------------------------------------------------------
790 # Changing the request time is like playing God
791 # --------------------------------------------------------------
792 if($hold->request_time ne $orig_hold->request_time) {
793 return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
794 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
797 # --------------------------------------------------------------
798 # if the hold is on the holds shelf or in transit and the pickup
799 # lib changes we need to create a new transit.
800 # --------------------------------------------------------------
801 if($orig_hold->pickup_lib ne $hold->pickup_lib) {
803 my $status = _hold_status($e, $hold);
805 if($status == 3) { # in transit
807 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
808 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
810 $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
812 # update the transit to reflect the new pickup location
813 my $transit = $e->search_action_hold_transit_copy(
814 {hold=>$hold->id, dest_recv_time => undef})->[0]
815 or return $e->die_event;
817 $transit->prev_dest($transit->dest); # mark the previous destination on the transit
818 $transit->dest($hold->pickup_lib);
819 $e->update_action_hold_transit_copy($transit) or return $e->die_event;
821 } elsif($status == 4) { # on holds shelf
823 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
824 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
826 $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
828 # create the new transit
829 my $evt = transit_hold($e, $orig_hold, $hold, $e->retrieve_asset_copy($hold->current_copy));
834 update_hold_if_frozen($self, $e, $hold, $orig_hold);
835 $e->update_action_hold_request($hold) or return $e->die_event;
838 # a change to mint-condition changes the set of potential copies, so retarget the hold;
839 if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
840 _reset_hold($self, $e->requestor, $hold)
847 my($e, $orig_hold, $hold, $copy) = @_;
848 my $src = $orig_hold->pickup_lib;
849 my $dest = $hold->pickup_lib;
851 $logger->info("putting hold into transit on pickup_lib update");
853 my $transit = Fieldmapper::action::hold_transit_copy->new;
854 $transit->hold($hold->id);
855 $transit->source($src);
856 $transit->dest($dest);
857 $transit->target_copy($copy->id);
858 $transit->source_send_time('now');
859 $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
861 $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
862 $copy->editor($e->requestor->id);
863 $copy->edit_date('now');
865 $e->create_action_hold_transit_copy($transit) or return $e->die_event;
866 $e->update_asset_copy($copy) or return $e->die_event;
870 # if the hold is frozen, this method ensures that the hold is not "targeted",
871 # that is, it clears the current_copy and prev_check_time to essentiallly
872 # reset the hold. If it is being activated, it runs the targeter in the background
873 sub update_hold_if_frozen {
874 my($self, $e, $hold, $orig_hold) = @_;
875 return if $hold->capture_time;
877 if($U->is_true($hold->frozen)) {
878 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
879 $hold->clear_current_copy;
880 $hold->clear_prev_check_time;
883 if($U->is_true($orig_hold->frozen)) {
884 $logger->info("Running targeter on activated hold ".$hold->id);
885 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
890 __PACKAGE__->register_method(
891 method => "hold_note_CUD",
892 api_name => "open-ils.circ.hold_request.note.cud",
894 desc => 'Create, update or delete a hold request note. If the operator (from Auth. token) '
895 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
897 { desc => 'Authentication token', type => 'string' },
898 { desc => 'Hold note object', type => 'object' }
901 desc => 'Returns the note ID, event on error'
907 my($self, $conn, $auth, $note) = @_;
909 my $e = new_editor(authtoken => $auth, xact => 1);
910 return $e->die_event unless $e->checkauth;
912 my $hold = $e->retrieve_action_hold_request($note->hold)
913 or return $e->die_event;
915 if($hold->usr ne $e->requestor->id) {
916 my $usr = $e->retrieve_actor_user($hold->usr);
917 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
918 $note->staff('t') if $note->isnew;
922 $e->create_action_hold_request_note($note) or return $e->die_event;
923 } elsif($note->ischanged) {
924 $e->update_action_hold_request_note($note) or return $e->die_event;
925 } elsif($note->isdeleted) {
926 $e->delete_action_hold_request_note($note) or return $e->die_event;
934 __PACKAGE__->register_method(
935 method => "retrieve_hold_status",
936 api_name => "open-ils.circ.hold.status.retrieve",
938 desc => 'Calculates the current status of the hold. The requestor must have ' .
939 'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
941 { desc => 'Hold ID', type => 'number' }
944 # type => 'number', # event sometimes
945 desc => <<'END_OF_DESC'
946 Returns event on error or:
947 -1 on error (for now),
948 1 for 'waiting for copy to become available',
949 2 for 'waiting for copy capture',
952 5 for 'hold-shelf-delay'
959 sub retrieve_hold_status {
960 my($self, $client, $auth, $hold_id) = @_;
962 my $e = new_editor(authtoken => $auth);
963 return $e->event unless $e->checkauth;
964 my $hold = $e->retrieve_action_hold_request($hold_id)
967 if( $e->requestor->id != $hold->usr ) {
968 return $e->event unless $e->allowed('VIEW_HOLD');
971 return _hold_status($e, $hold);
977 if ($hold->cancel_time) {
980 return 1 unless $hold->current_copy;
981 return 2 unless $hold->capture_time;
983 my $copy = $hold->current_copy;
984 unless( ref $copy ) {
985 $copy = $e->retrieve_asset_copy($hold->current_copy)
989 return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
991 if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
993 my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
994 return 4 unless $hs_wait_interval;
996 # if a hold_shelf_status_delay interval is defined and start_time plus
997 # the interval is greater than now, consider the hold to be in the virtual
998 # "on its way to the holds shelf" status. Return 5.
1000 my $transit = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
1001 my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
1002 $start_time = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
1003 my $end_time = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
1005 return 5 if $end_time > DateTime->now;
1014 __PACKAGE__->register_method(
1015 method => "retrieve_hold_queue_stats",
1016 api_name => "open-ils.circ.hold.queue_stats.retrieve",
1018 desc => 'Returns summary data about the state of a hold',
1020 { desc => 'Authentication token', type => 'string'},
1021 { desc => 'Hold ID', type => 'number'},
1024 desc => q/Summary object with keys:
1025 total_holds : total holds in queue
1026 queue_position : current queue position
1027 potential_copies : number of potential copies for this hold
1028 estimated_wait : estimated wait time in days
1029 status : hold status
1030 -1 => error or unexpected state,
1031 1 => 'waiting for copy to become available',
1032 2 => 'waiting for copy capture',
1035 5 => 'hold-shelf-delay'
1042 sub retrieve_hold_queue_stats {
1043 my($self, $conn, $auth, $hold_id) = @_;
1044 my $e = new_editor(authtoken => $auth);
1045 return $e->event unless $e->checkauth;
1046 my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1047 if($e->requestor->id != $hold->usr) {
1048 return $e->event unless $e->allowed('VIEW_HOLD');
1050 return retrieve_hold_queue_status_impl($e, $hold);
1053 sub retrieve_hold_queue_status_impl {
1057 # The holds queue is defined as the distinct set of holds that share at
1058 # least one potential copy with the context hold, plus any holds that
1059 # share the same hold type and target. The latter part exists to
1060 # accomodate holds that currently have no potential copies
1061 my $q_holds = $e->json_query({
1063 # fetch cut_in_line and request_time since they're in the order_by
1064 # and we're asking for distinct values
1065 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1066 from => { ahr => 'ahcm' },
1070 "field" => "cut_in_line",
1071 "transform" => "coalesce",
1073 "direction" => "desc"
1075 { "class" => "ahr", "field" => "request_time" }
1082 select => {ahcm => ['target_copy']},
1084 where => {hold => $hold->id}
1091 if (!@$q_holds) { # none? maybe we don't have a map ...
1092 $q_holds = $e->json_query({
1093 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1098 "field" => "cut_in_line",
1099 "transform" => "coalesce",
1101 "direction" => "desc"
1103 { "class" => "ahr", "field" => "request_time" }
1106 hold_type => $hold->hold_type,
1107 target => $hold->target
1114 for my $h (@$q_holds) {
1115 last if $h->{id} == $hold->id;
1119 my $hold_data = $e->json_query({
1121 acp => [ {column => 'id', transform => 'count', aggregate => 1, alias => 'count'} ],
1122 ccm => [ {column =>'avg_wait_time'} ]
1128 ccm => {type => 'left'}
1133 where => {'+ahcm' => {hold => $hold->id} }
1136 my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1138 my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1139 my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1140 $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1141 $default_wait ||= '0 seconds';
1143 # Estimated wait time is the average wait time across the set
1144 # of potential copies, divided by the number of potential copies
1145 # times the queue position.
1147 my $combined_secs = 0;
1148 my $num_potentials = 0;
1150 for my $wait_data (@$hold_data) {
1151 my $count += $wait_data->{count};
1152 $combined_secs += $count *
1153 OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1154 $num_potentials += $count;
1157 my $estimated_wait = -1;
1159 if($num_potentials) {
1160 my $avg_wait = $combined_secs / $num_potentials;
1161 $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1162 $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1166 total_holds => scalar(@$q_holds),
1167 queue_position => $qpos,
1168 potential_copies => $num_potentials,
1169 status => _hold_status( $e, $hold ),
1170 estimated_wait => int($estimated_wait)
1175 sub fetch_open_hold_by_current_copy {
1178 my $hold = $apputils->simplereq(
1180 'open-ils.cstore.direct.action.hold_request.search.atomic',
1181 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1182 return $hold->[0] if ref($hold);
1186 sub fetch_related_holds {
1189 return $apputils->simplereq(
1191 'open-ils.cstore.direct.action.hold_request.search.atomic',
1192 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1196 __PACKAGE__->register_method(
1197 method => "hold_pull_list",
1198 api_name => "open-ils.circ.hold_pull_list.retrieve",
1200 desc => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1201 'The location is determined by the login session.',
1203 { desc => 'Limit (optional)', type => 'number'},
1204 { desc => 'Offset (optional)', type => 'number'},
1207 desc => 'reference to a list of holds, or event on failure',
1212 __PACKAGE__->register_method(
1213 method => "hold_pull_list",
1214 api_name => "open-ils.circ.hold_pull_list.id_list.retrieve",
1216 desc => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1217 'The location is determined by the login session.',
1219 { desc => 'Limit (optional)', type => 'number'},
1220 { desc => 'Offset (optional)', type => 'number'},
1223 desc => 'reference to a list of holds, or event on failure',
1228 __PACKAGE__->register_method(
1229 method => "hold_pull_list",
1230 api_name => "open-ils.circ.hold_pull_list.retrieve.count",
1232 desc => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1233 'The location is determined by the login session.',
1235 { desc => 'Limit (optional)', type => 'number'},
1236 { desc => 'Offset (optional)', type => 'number'},
1239 desc => 'Holds count (integer), or event on failure',
1246 sub hold_pull_list {
1247 my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1248 my( $reqr, $evt ) = $U->checkses($authtoken);
1249 return $evt if $evt;
1251 my $org = $reqr->ws_ou || $reqr->home_ou;
1252 # the perm locaiton shouldn't really matter here since holds
1253 # will exist all over and VIEW_HOLDS should be universal
1254 $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1255 return $evt if $evt;
1257 if($self->api_name =~ /count/) {
1259 my $count = $U->storagereq(
1260 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1261 $org, $limit, $offset );
1263 $logger->info("Grabbing pull list for org unit $org with $count items");
1266 } elsif( $self->api_name =~ /id_list/ ) {
1267 return $U->storagereq(
1268 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1269 $org, $limit, $offset );
1272 return $U->storagereq(
1273 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1274 $org, $limit, $offset );
1278 __PACKAGE__->register_method(
1279 method => "print_hold_pull_list",
1280 api_name => "open-ils.circ.hold_pull_list.print",
1282 desc => 'Returns an HTML-formatted holds pull list',
1284 { desc => 'Authtoken', type => 'string'},
1285 { desc => 'Org unit ID. Optional, defaults to workstation org unit', type => 'number'},
1288 desc => 'HTML string',
1294 sub print_hold_pull_list {
1295 my($self, $client, $auth, $org_id) = @_;
1297 my $e = new_editor(authtoken=>$auth);
1298 return $e->event unless $e->checkauth;
1300 $org_id = (defined $org_id) ? $org_id : $e->requestor->ws_ou;
1301 return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1303 my $hold_ids = $U->storagereq(
1304 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1307 return undef unless @$hold_ids;
1309 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1311 # Holds will /NOT/ be in order after this ...
1312 my $holds = $e->search_action_hold_request({id => $hold_ids}, {substream => 1});
1313 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1315 # ... so we must resort.
1316 my $hold_map = +{map { $_->id => $_ } @$holds};
1317 my $sorted_holds = [];
1318 push @$sorted_holds, $hold_map->{$_} foreach @$hold_ids;
1320 return $U->fire_object_event(
1321 undef, "ahr.format.pull_list", $sorted_holds,
1322 $org_id, undef, undef, $client
1327 __PACKAGE__->register_method(
1328 method => "print_hold_pull_list_stream",
1330 api_name => "open-ils.circ.hold_pull_list.print.stream",
1332 desc => 'Returns a stream of fleshed holds',
1334 { desc => 'Authtoken', type => 'string'},
1335 { desc => 'Hash of optional param: Org unit ID (defaults to workstation org unit), limit, offset, sort (array of: acplo.position, call_number, request_time)',
1340 desc => 'A stream of fleshed holds',
1346 sub print_hold_pull_list_stream {
1347 my($self, $client, $auth, $params) = @_;
1349 my $e = new_editor(authtoken=>$auth);
1350 return $e->die_event unless $e->checkauth;
1352 delete($$params{org_id}) unless (int($$params{org_id}));
1353 delete($$params{limit}) unless (int($$params{limit}));
1354 delete($$params{offset}) unless (int($$params{offset}));
1355 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1356 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1357 $$params{chunk_size} ||= 10;
1359 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1360 return $e->die_event unless $e->allowed('VIEW_HOLD', $$params{org_id });
1363 if ($$params{sort} && @{ $$params{sort} }) {
1364 for my $s (@{ $$params{sort} }) {
1365 if ($s eq 'acplo.position') {
1367 "class" => "acplo", "field" => "position",
1368 "transform" => "coalesce", "params" => [999]
1370 } elsif ($s eq 'call_number') {
1371 push @$sort, {"class" => "acn", "field" => "label"};
1372 } elsif ($s eq 'request_time') {
1373 push @$sort, {"class" => "ahr", "field" => "request_time"};
1377 push @$sort, {"class" => "ahr", "field" => "request_time"};
1380 my $holds_ids = $e->json_query(
1382 "select" => {"ahr" => ["id"]},
1387 "fkey" => "current_copy",
1389 "circ_lib" => $$params{org_id}, "status" => [0,7]
1394 "fkey" => "call_number"
1398 "fkey" => "circ_lib",
1401 "location" => {"=" => {"+acp" => "location"}}
1410 "capture_time" => undef,
1411 "cancel_time" => undef,
1413 {"expire_time" => undef },
1414 {"expire_time" => {">" => "now"}}
1418 (@$sort ? (order_by => $sort) : ()),
1419 ($$params{limit} ? (limit => $$params{limit}) : ()),
1420 ($$params{offset} ? (offset => $$params{offset}) : ())
1421 }, {"substream" => 1}
1422 ) or return $e->die_event;
1424 $logger->info("about to stream back " . scalar(@$holds_ids) . " holds");
1427 for my $hid (@$holds_ids) {
1428 push @chunk, $e->retrieve_action_hold_request([
1432 "ahr" => ["usr", "current_copy"],
1434 "acp" => ["location", "call_number"],
1440 if (@chunk >= $$params{chunk_size}) {
1441 $client->respond( \@chunk );
1445 $client->respond_complete( \@chunk ) if (@chunk);
1452 __PACKAGE__->register_method(
1453 method => 'fetch_hold_notify',
1454 api_name => 'open-ils.circ.hold_notification.retrieve_by_hold',
1457 Returns a list of hold notification objects based on hold id.
1458 @param authtoken The loggin session key
1459 @param holdid The id of the hold whose notifications we want to retrieve
1460 @return An array of hold notification objects, event on error.
1464 sub fetch_hold_notify {
1465 my( $self, $conn, $authtoken, $holdid ) = @_;
1466 my( $requestor, $evt ) = $U->checkses($authtoken);
1467 return $evt if $evt;
1468 my ($hold, $patron);
1469 ($hold, $evt) = $U->fetch_hold($holdid);
1470 return $evt if $evt;
1471 ($patron, $evt) = $U->fetch_user($hold->usr);
1472 return $evt if $evt;
1474 $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1475 return $evt if $evt;
1477 $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1478 return $U->cstorereq(
1479 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1483 __PACKAGE__->register_method(
1484 method => 'create_hold_notify',
1485 api_name => 'open-ils.circ.hold_notification.create',
1487 Creates a new hold notification object
1488 @param authtoken The login session key
1489 @param notification The hold notification object to create
1490 @return ID of the new object on success, Event on error
1494 sub create_hold_notify {
1495 my( $self, $conn, $auth, $note ) = @_;
1496 my $e = new_editor(authtoken=>$auth, xact=>1);
1497 return $e->die_event unless $e->checkauth;
1499 my $hold = $e->retrieve_action_hold_request($note->hold)
1500 or return $e->die_event;
1501 my $patron = $e->retrieve_actor_user($hold->usr)
1502 or return $e->die_event;
1504 return $e->die_event unless
1505 $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1507 $note->notify_staff($e->requestor->id);
1508 $e->create_action_hold_notification($note) or return $e->die_event;
1513 __PACKAGE__->register_method(
1514 method => 'create_hold_note',
1515 api_name => 'open-ils.circ.hold_note.create',
1517 Creates a new hold request note object
1518 @param authtoken The login session key
1519 @param note The hold note object to create
1520 @return ID of the new object on success, Event on error
1524 sub create_hold_note {
1525 my( $self, $conn, $auth, $note ) = @_;
1526 my $e = new_editor(authtoken=>$auth, xact=>1);
1527 return $e->die_event unless $e->checkauth;
1529 my $hold = $e->retrieve_action_hold_request($note->hold)
1530 or return $e->die_event;
1531 my $patron = $e->retrieve_actor_user($hold->usr)
1532 or return $e->die_event;
1534 return $e->die_event unless
1535 $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn. Probably want something more specific
1537 $e->create_action_hold_request_note($note) or return $e->die_event;
1542 __PACKAGE__->register_method(
1543 method => 'reset_hold',
1544 api_name => 'open-ils.circ.hold.reset',
1546 Un-captures and un-targets a hold, essentially returning
1547 it to the state it was in directly after it was placed,
1548 then attempts to re-target the hold
1549 @param authtoken The login session key
1550 @param holdid The id of the hold
1556 my( $self, $conn, $auth, $holdid ) = @_;
1558 my ($hold, $evt) = $U->fetch_hold($holdid);
1559 return $evt if $evt;
1560 ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1561 return $evt if $evt;
1562 $evt = _reset_hold($self, $reqr, $hold);
1563 return $evt if $evt;
1568 __PACKAGE__->register_method(
1569 method => 'reset_hold_batch',
1570 api_name => 'open-ils.circ.hold.reset.batch'
1573 sub reset_hold_batch {
1574 my($self, $conn, $auth, $hold_ids) = @_;
1576 my $e = new_editor(authtoken => $auth);
1577 return $e->event unless $e->checkauth;
1579 for my $hold_id ($hold_ids) {
1581 my $hold = $e->retrieve_action_hold_request(
1582 [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}])
1583 or return $e->event;
1585 next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1586 _reset_hold($self, $e->requestor, $hold);
1594 my ($self, $reqr, $hold) = @_;
1596 my $e = new_editor(xact =>1, requestor => $reqr);
1598 $logger->info("reseting hold ".$hold->id);
1600 my $hid = $hold->id;
1602 if( $hold->capture_time and $hold->current_copy ) {
1604 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1605 or return $e->die_event;
1607 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1608 $logger->info("setting copy to status 'reshelving' on hold retarget");
1609 $copy->status(OILS_COPY_STATUS_RESHELVING);
1610 $copy->editor($e->requestor->id);
1611 $copy->edit_date('now');
1612 $e->update_asset_copy($copy) or return $e->die_event;
1614 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1616 # We don't want the copy to remain "in transit"
1617 $copy->status(OILS_COPY_STATUS_RESHELVING);
1618 $logger->warn("! reseting hold [$hid] that is in transit");
1619 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1622 my $trans = $e->retrieve_action_transit_copy($transid);
1624 $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1625 my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1);
1626 $logger->info("Transit abort completed with result $evt");
1627 unless ("$evt" eq 1) {
1636 $hold->clear_capture_time;
1637 $hold->clear_current_copy;
1638 $hold->clear_shelf_time;
1639 $hold->clear_shelf_expire_time;
1641 $e->update_action_hold_request($hold) or return $e->die_event;
1645 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1651 __PACKAGE__->register_method(
1652 method => 'fetch_open_title_holds',
1653 api_name => 'open-ils.circ.open_holds.retrieve',
1655 Returns a list ids of un-fulfilled holds for a given title id
1656 @param authtoken The login session key
1657 @param id the id of the item whose holds we want to retrieve
1658 @param type The hold type - M, T, I, V, C, F, R
1662 sub fetch_open_title_holds {
1663 my( $self, $conn, $auth, $id, $type, $org ) = @_;
1664 my $e = new_editor( authtoken => $auth );
1665 return $e->event unless $e->checkauth;
1668 $org ||= $e->requestor->ws_ou;
1670 # return $e->search_action_hold_request(
1671 # { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1673 # XXX make me return IDs in the future ^--
1674 my $holds = $e->search_action_hold_request(
1677 cancel_time => undef,
1679 fulfillment_time => undef
1683 flesh_hold_transits($holds);
1688 sub flesh_hold_transits {
1690 for my $hold ( @$holds ) {
1692 $apputils->simplereq(
1694 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1695 { hold => $hold->id },
1696 { order_by => { ahtc => 'id desc' }, limit => 1 }
1702 sub flesh_hold_notices {
1703 my( $holds, $e ) = @_;
1704 $e ||= new_editor();
1706 for my $hold (@$holds) {
1707 my $notices = $e->search_action_hold_notification(
1709 { hold => $hold->id },
1710 { order_by => { anh => 'notify_time desc' } },
1715 $hold->notify_count(scalar(@$notices));
1717 my $n = $e->retrieve_action_hold_notification($$notices[0])
1718 or return $e->event;
1719 $hold->notify_time($n->notify_time);
1725 __PACKAGE__->register_method(
1726 method => 'fetch_captured_holds',
1727 api_name => 'open-ils.circ.captured_holds.on_shelf.retrieve',
1730 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
1731 @param authtoken The login session key
1732 @param org The org id of the location in question
1736 __PACKAGE__->register_method(
1737 method => 'fetch_captured_holds',
1738 api_name => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
1741 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
1742 @param authtoken The login session key
1743 @param org The org id of the location in question
1747 __PACKAGE__->register_method(
1748 method => 'fetch_captured_holds',
1749 api_name => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
1752 Returns list ids of shelf-expired un-fulfilled holds for a given title id
1753 @param authtoken The login session key
1754 @param org The org id of the location in question
1759 sub fetch_captured_holds {
1760 my( $self, $conn, $auth, $org ) = @_;
1762 my $e = new_editor(authtoken => $auth);
1763 return $e->die_event unless $e->checkauth;
1764 return $e->die_event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
1766 $org ||= $e->requestor->ws_ou;
1769 select => { ahr => ['id'] },
1774 fkey => 'current_copy'
1779 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
1781 capture_time => { "!=" => undef },
1782 current_copy => { "!=" => undef },
1783 fulfillment_time => undef,
1785 cancel_time => undef,
1789 if($self->api_name =~ /expired/) {
1790 $query->{'where'}->{'+ahr'}->{'shelf_expire_time'} = {'<' => 'now'};
1791 $query->{'where'}->{'+ahr'}->{'shelf_time'} = {'!=' => undef};
1793 my $hold_ids = $e->json_query( $query );
1795 for my $hold_id (@$hold_ids) {
1796 if($self->api_name =~ /id_list/) {
1797 $conn->respond($hold_id->{id});
1801 $e->retrieve_action_hold_request([
1805 flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
1806 order_by => {anh => 'notify_time desc'}
1816 __PACKAGE__->register_method(
1817 method => "print_expired_holds_stream",
1818 api_name => "open-ils.circ.captured_holds.expired.print.stream",
1822 sub print_expired_holds_stream {
1823 my ($self, $client, $auth, $params) = @_;
1825 # No need to check specific permissions: we're going to call another method
1826 # that will do that.
1827 my $e = new_editor("authtoken" => $auth);
1828 return $e->die_event unless $e->checkauth;
1830 delete($$params{org_id}) unless (int($$params{org_id}));
1831 delete($$params{limit}) unless (int($$params{limit}));
1832 delete($$params{offset}) unless (int($$params{offset}));
1833 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1834 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1835 $$params{chunk_size} ||= 10;
1837 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1839 my @hold_ids = $self->method_lookup(
1840 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
1841 )->run($auth, $params->{"org_id"});
1846 } elsif (defined $U->event_code($hold_ids[0])) {
1848 return $hold_ids[0];
1851 $logger->info("about to stream back up to " . scalar(@hold_ids) . " expired holds");
1854 my @hid_chunk = splice @hold_ids, 0, $params->{"chunk_size"};
1856 my $result_chunk = $e->json_query({
1858 "acp" => ["barcode"],
1860 first_given_name second_given_name family_name alias
1869 "field" => "id", "fkey" => "current_copy",
1872 "field" => "id", "fkey" => "call_number",
1875 "field" => "id", "fkey" => "record"
1879 "acpl" => {"field" => "id", "fkey" => "location"}
1882 "au" => {"field" => "id", "fkey" => "usr"}
1885 "where" => {"+ahr" => {"id" => \@hid_chunk}}
1886 }) or return $e->die_event;
1887 $client->respond($result_chunk);
1894 __PACKAGE__->register_method(
1895 method => "check_title_hold_batch",
1896 api_name => "open-ils.circ.title_hold.is_possible.batch",
1899 desc => '@see open-ils.circ.title_hold.is_possible.batch',
1901 { desc => 'Authentication token', type => 'string'},
1902 { desc => 'Array of Hash of named parameters', type => 'array'},
1905 desc => 'Array of response objects',
1911 sub check_title_hold_batch {
1912 my($self, $client, $authtoken, $param_list) = @_;
1913 foreach (@$param_list) {
1914 my ($res) = $self->method_lookup('open-ils.circ.title_hold.is_possible')->run($authtoken, $_);
1915 $client->respond($res);
1921 __PACKAGE__->register_method(
1922 method => "check_title_hold",
1923 api_name => "open-ils.circ.title_hold.is_possible",
1925 desc => 'Determines if a hold were to be placed by a given user, ' .
1926 'whether or not said hold would have any potential copies to fulfill it.' .
1927 'The named paramaters of the second argument include: ' .
1928 'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
1929 'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' ,
1931 { desc => 'Authentication token', type => 'string'},
1932 { desc => 'Hash of named parameters', type => 'object'},
1935 desc => 'List of new message IDs (empty if none)',
1941 =head3 check_title_hold (token, hash)
1943 The named fields in the hash are:
1945 patronid - ID of the hold recipient (required)
1946 depth - hold range depth (default 0)
1947 pickup_lib - destination for hold, fallback value for selection_ou
1948 selection_ou - ID of org_unit establishing hard and soft hold boundary settings
1949 issuanceid - ID of the issuance to be held, required for Issuance level hold
1950 titleid - ID (BRN) of the title to be held, required for Title level hold
1951 volume_id - required for Volume level hold
1952 copy_id - required for Copy level hold
1953 mrid - required for Meta-record level hold
1954 hold_type - T, C (or R or F), I, V or M for Title, Copy, Issuance, Volume or Meta-record (default "T")
1956 All key/value pairs are passed on to do_possibility_checks.
1960 # FIXME: better params checking. what other params are required, if any?
1961 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
1962 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still
1963 # used in conditionals, where it may be undefined, causing a warning.
1964 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
1966 sub check_title_hold {
1967 my( $self, $client, $authtoken, $params ) = @_;
1968 my $e = new_editor(authtoken=>$authtoken);
1969 return $e->event unless $e->checkauth;
1971 my %params = %$params;
1972 my $depth = $params{depth} || 0;
1973 my $selection_ou = $params{selection_ou} || $params{pickup_lib};
1975 my $patron = $e->retrieve_actor_user($params{patronid})
1976 or return $e->event;
1978 if( $e->requestor->id ne $patron->id ) {
1979 return $e->event unless
1980 $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
1983 return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
1985 my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
1986 or return $e->event;
1988 my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
1989 my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
1992 my $return_depth = $hard_boundary; # default depth to return on success
1993 if(defined $soft_boundary and $depth < $soft_boundary) {
1994 # work up the tree and as soon as we find a potential copy, use that depth
1995 # also, make sure we don't go past the hard boundary if it exists
1997 # our min boundary is the greater of user-specified boundary or hard boundary
1998 my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?
1999 $hard_boundary : $depth;
2001 my $depth = $soft_boundary;
2002 while($depth >= $min_depth) {
2003 $logger->info("performing hold possibility check with soft boundary $depth");
2004 @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
2006 $return_depth = $depth;
2011 } elsif(defined $hard_boundary and $depth < $hard_boundary) {
2012 # there is no soft boundary, enforce the hard boundary if it exists
2013 $logger->info("performing hold possibility check with hard boundary $hard_boundary");
2014 @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
2016 # no boundaries defined, fall back to user specifed boundary or no boundary
2017 $logger->info("performing hold possibility check with no boundary");
2018 @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
2024 "depth" => $return_depth,
2025 "local_avail" => $status[1]
2027 } elsif ($status[2]) {
2028 my $n = scalar @{$status[2]};
2029 return {"success" => 0, "last_event" => $status[2]->[$n - 1]};
2031 return {"success" => 0};
2037 sub do_possibility_checks {
2038 my($e, $patron, $request_lib, $depth, %params) = @_;
2040 my $issuanceid = $params{issuanceid} || "";
2041 my $titleid = $params{titleid} || "";
2042 my $volid = $params{volume_id};
2043 my $copyid = $params{copy_id};
2044 my $mrid = $params{mrid} || "";
2045 my $pickup_lib = $params{pickup_lib};
2046 my $hold_type = $params{hold_type} || 'T';
2047 my $selection_ou = $params{selection_ou} || $pickup_lib;
2054 if( $hold_type eq OILS_HOLD_TYPE_FORCE || $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_COPY ) {
2056 return $e->event unless $copy = $e->retrieve_asset_copy($copyid);
2057 return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
2058 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2060 return verify_copy_for_hold(
2061 $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib
2064 } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2066 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
2067 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2069 return _check_volume_hold_is_possible(
2070 $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2073 } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
2075 return _check_title_hold_is_possible(
2076 $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2079 } elsif( $hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2081 return _check_issuance_hold_is_possible(
2082 $issuanceid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2085 } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2087 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
2088 my @recs = map { $_->source } @$maps;
2090 for my $rec (@recs) {
2091 @status = _check_title_hold_is_possible(
2092 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2098 # else { Unrecognized hold_type ! } # FIXME: return error? or 0?
2102 sub create_ranged_org_filter {
2103 my($e, $selection_ou, $depth) = @_;
2105 # find the orgs from which this hold may be fulfilled,
2106 # based on the selection_ou and depth
2108 my $top_org = $e->search_actor_org_unit([
2109 {parent_ou => undef},
2110 {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
2113 return () if $depth == $top_org->ou_type->depth;
2115 my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
2116 %org_filter = (circ_lib => []);
2117 push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
2119 $logger->info("hold org filter at depth $depth and selection_ou ".
2120 "$selection_ou created list of @{$org_filter{circ_lib}}");
2126 sub _check_title_hold_is_possible {
2127 my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2129 my $e = new_editor();
2130 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2132 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2133 my $copies = $e->json_query(
2135 select => { acp => ['id', 'circ_lib'] },
2140 fkey => 'call_number',
2144 filter => { id => $titleid },
2149 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2150 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2154 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2159 $logger->info("title possible found ".scalar(@$copies)." potential copies");
2163 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2164 "payload" => {"fail_part" => "no_ultimate_items"}
2169 # -----------------------------------------------------------------------
2170 # sort the copies into buckets based on their circ_lib proximity to
2171 # the patron's home_ou.
2172 # -----------------------------------------------------------------------
2174 my $home_org = $patron->home_ou;
2175 my $req_org = $request_lib->id;
2177 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2179 $prox_cache{$home_org} =
2180 $e->search_actor_org_unit_proximity({from_org => $home_org})
2181 unless $prox_cache{$home_org};
2182 my $home_prox = $prox_cache{$home_org};
2185 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2186 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2188 my @keys = sort { $a <=> $b } keys %buckets;
2191 if( $home_org ne $req_org ) {
2192 # -----------------------------------------------------------------------
2193 # shove the copies close to the request_lib into the primary buckets
2194 # directly before the farthest away copies. That way, they are not
2195 # given priority, but they are checked before the farthest copies.
2196 # -----------------------------------------------------------------------
2197 $prox_cache{$req_org} =
2198 $e->search_actor_org_unit_proximity({from_org => $req_org})
2199 unless $prox_cache{$req_org};
2200 my $req_prox = $prox_cache{$req_org};
2203 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2204 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2206 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2207 my $new_key = $highest_key - 0.5; # right before the farthest prox
2208 my @keys2 = sort { $a <=> $b } keys %buckets2;
2209 for my $key (@keys2) {
2210 last if $key >= $highest_key;
2211 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2215 @keys = sort { $a <=> $b } keys %buckets;
2220 OUTER: for my $key (@keys) {
2221 my @cps = @{$buckets{$key}};
2223 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2225 for my $copyid (@cps) {
2227 next if $seen{$copyid};
2228 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2229 my $copy = $e->retrieve_asset_copy($copyid);
2230 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2232 unless($title) { # grab the title if we don't already have it
2233 my $vol = $e->retrieve_asset_call_number(
2234 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2235 $title = $vol->record;
2238 @status = verify_copy_for_hold(
2239 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2241 last OUTER if $status[0];
2248 sub _check_issuance_hold_is_possible {
2249 my( $issuanceid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2251 my $e = new_editor();
2252 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2254 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2255 my $copies = $e->json_query(
2257 select => { acp => ['id', 'circ_lib'] },
2263 filter => { issuance => $issuanceid }
2265 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2266 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2270 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2276 $logger->info("issuance possible found ".scalar(@$copies)." potential copies");
2280 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2281 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2286 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2287 "payload" => {"fail_part" => "no_ultimate_items"}
2295 # -----------------------------------------------------------------------
2296 # sort the copies into buckets based on their circ_lib proximity to
2297 # the patron's home_ou.
2298 # -----------------------------------------------------------------------
2300 my $home_org = $patron->home_ou;
2301 my $req_org = $request_lib->id;
2303 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2305 $prox_cache{$home_org} =
2306 $e->search_actor_org_unit_proximity({from_org => $home_org})
2307 unless $prox_cache{$home_org};
2308 my $home_prox = $prox_cache{$home_org};
2311 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2312 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2314 my @keys = sort { $a <=> $b } keys %buckets;
2317 if( $home_org ne $req_org ) {
2318 # -----------------------------------------------------------------------
2319 # shove the copies close to the request_lib into the primary buckets
2320 # directly before the farthest away copies. That way, they are not
2321 # given priority, but they are checked before the farthest copies.
2322 # -----------------------------------------------------------------------
2323 $prox_cache{$req_org} =
2324 $e->search_actor_org_unit_proximity({from_org => $req_org})
2325 unless $prox_cache{$req_org};
2326 my $req_prox = $prox_cache{$req_org};
2329 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2330 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2332 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2333 my $new_key = $highest_key - 0.5; # right before the farthest prox
2334 my @keys2 = sort { $a <=> $b } keys %buckets2;
2335 for my $key (@keys2) {
2336 last if $key >= $highest_key;
2337 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2341 @keys = sort { $a <=> $b } keys %buckets;
2346 OUTER: for my $key (@keys) {
2347 my @cps = @{$buckets{$key}};
2349 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2351 for my $copyid (@cps) {
2353 next if $seen{$copyid};
2354 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2355 my $copy = $e->retrieve_asset_copy($copyid);
2356 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2358 unless($title) { # grab the title if we don't already have it
2359 my $vol = $e->retrieve_asset_call_number(
2360 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2361 $title = $vol->record;
2364 @status = verify_copy_for_hold(
2365 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2367 last OUTER if $status[0];
2372 if (!defined($empty_ok)) {
2373 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2374 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2377 return (1,0) if ($empty_ok);
2383 sub _check_volume_hold_is_possible {
2384 my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2385 my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
2386 my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
2387 $logger->info("checking possibility of volume hold for volume ".$vol->id);
2392 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2393 "payload" => {"fail_part" => "no_ultimate_items"}
2399 for my $copy ( @$copies ) {
2400 @status = verify_copy_for_hold(
2401 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
2409 sub verify_copy_for_hold {
2410 my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib ) = @_;
2411 $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
2412 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2413 { patron => $patron,
2414 requestor => $requestor,
2417 title_descriptor => $title->fixed_fields, # this is fleshed into the title object
2418 pickup_lib => $pickup_lib,
2419 request_lib => $request_lib,
2421 show_event_list => 1
2426 (not scalar @$permitted), # true if permitted is an empty arrayref
2428 ($copy->circ_lib == $pickup_lib) and
2429 ($copy->status == OILS_COPY_STATUS_AVAILABLE)
2437 sub find_nearest_permitted_hold {
2440 my $editor = shift; # CStoreEditor object
2441 my $copy = shift; # copy to target
2442 my $user = shift; # staff
2443 my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
2445 my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
2447 my $bc = $copy->barcode;
2449 # find any existing holds that already target this copy
2450 my $old_holds = $editor->search_action_hold_request(
2451 { current_copy => $copy->id,
2452 cancel_time => undef,
2453 capture_time => undef
2457 # hold->type "R" means we need this copy
2458 for my $h (@$old_holds) { return ($h) if $h->hold_type eq 'R'; }
2461 my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
2463 $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
2464 " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
2466 my $fifo = $U->ou_ancestor_setting_value($user->ws_ou, 'circ.holds_fifo');
2468 # search for what should be the best holds for this copy to fulfill
2469 my $best_holds = $U->storagereq(
2470 "open-ils.storage.action.hold_request.nearest_hold.atomic",
2471 $user->ws_ou, $copy->id, 10, $hold_stall_interval, $fifo );
2473 unless(@$best_holds) {
2475 if( my $hold = $$old_holds[0] ) {
2476 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2480 $logger->info("circulator: no suitable holds found for copy $bc");
2481 return (undef, $evt);
2487 # for each potential hold, we have to run the permit script
2488 # to make sure the hold is actually permitted.
2491 for my $holdid (@$best_holds) {
2492 next unless $holdid;
2493 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
2495 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
2496 my $reqr = $reqr_cache{$hold->requestor} || $editor->retrieve_actor_user($hold->requestor);
2497 my $rlib = $org_cache{$hold->request_lib} || $editor->retrieve_actor_org_unit($hold->request_lib);
2499 $reqr_cache{$hold->requestor} = $reqr;
2500 $org_cache{$hold->request_lib} = $rlib;
2502 # see if this hold is permitted
2503 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2504 { patron_id => $hold->usr,
2507 pickup_lib => $hold->pickup_lib,
2508 request_lib => $rlib,
2520 unless( $best_hold ) { # no "good" permitted holds were found
2521 if( my $hold = $$old_holds[0] ) { # can we return a pre-targeted hold?
2522 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2527 $logger->info("circulator: no suitable holds found for copy $bc");
2528 return (undef, $evt);
2531 $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
2533 # indicate a permitted hold was found
2534 return $best_hold if $check_only;
2536 # we've found a permitted hold. we need to "grab" the copy
2537 # to prevent re-targeted holds (next part) from re-grabbing the copy
2538 $best_hold->current_copy($copy->id);
2539 $editor->update_action_hold_request($best_hold)
2540 or return (undef, $editor->event);
2545 # re-target any other holds that already target this copy
2546 for my $old_hold (@$old_holds) {
2547 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
2548 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
2549 $old_hold->id." after a better hold [".$best_hold->id."] was found");
2550 $old_hold->clear_current_copy;
2551 $old_hold->clear_prev_check_time;
2552 $editor->update_action_hold_request($old_hold)
2553 or return (undef, $editor->event);
2554 push(@retarget, $old_hold->id);
2557 return ($best_hold, undef, (@retarget) ? \@retarget : undef);
2565 __PACKAGE__->register_method(
2566 method => 'all_rec_holds',
2567 api_name => 'open-ils.circ.holds.retrieve_all_from_title',
2571 my( $self, $conn, $auth, $title_id, $args ) = @_;
2573 my $e = new_editor(authtoken=>$auth);
2574 $e->checkauth or return $e->event;
2575 $e->allowed('VIEW_HOLD') or return $e->event;
2578 $args->{fulfillment_time} = undef; # we don't want to see old fulfilled holds
2579 $args->{cancel_time} = undef;
2581 my $resp = { volume_holds => [], copy_holds => [], metarecord_holds => [] };
2583 my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
2585 $resp->{metarecord_holds} = $e->search_action_hold_request(
2586 { hold_type => OILS_HOLD_TYPE_METARECORD,
2587 target => $mr_map->metarecord,
2593 $resp->{title_holds} = $e->search_action_hold_request(
2595 hold_type => OILS_HOLD_TYPE_TITLE,
2596 target => $title_id,
2600 my $vols = $e->search_asset_call_number(
2601 { record => $title_id, deleted => 'f' }, {idlist=>1});
2603 return $resp unless @$vols;
2605 $resp->{volume_holds} = $e->search_action_hold_request(
2607 hold_type => OILS_HOLD_TYPE_VOLUME,
2612 my $copies = $e->search_asset_copy(
2613 { call_number => $vols, deleted => 'f' }, {idlist=>1});
2615 return $resp unless @$copies;
2617 $resp->{copy_holds} = $e->search_action_hold_request(
2619 hold_type => OILS_HOLD_TYPE_COPY,
2631 __PACKAGE__->register_method(
2632 method => 'uber_hold',
2634 api_name => 'open-ils.circ.hold.details.retrieve'
2638 my($self, $client, $auth, $hold_id, $args) = @_;
2639 my $e = new_editor(authtoken=>$auth);
2640 $e->checkauth or return $e->event;
2641 return uber_hold_impl($e, $hold_id, $args);
2644 __PACKAGE__->register_method(
2645 method => 'batch_uber_hold',
2648 api_name => 'open-ils.circ.hold.details.batch.retrieve'
2651 sub batch_uber_hold {
2652 my($self, $client, $auth, $hold_ids, $args) = @_;
2653 my $e = new_editor(authtoken=>$auth);
2654 $e->checkauth or return $e->event;
2655 $client->respond(uber_hold_impl($e, $_, $args)) for @$hold_ids;
2659 sub uber_hold_impl {
2660 my($e, $hold_id, $args) = @_;
2665 my $hold = $e->retrieve_action_hold_request(
2670 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
2673 ) or return $e->event;
2675 if($hold->usr->id ne $e->requestor->id) {
2676 # A user is allowed to see his/her own holds
2677 $e->allowed('VIEW_HOLD') or return $e->event;
2678 $hold->notes( # filter out any non-staff ("private") notes
2679 [ grep { !$U->is_true($_->staff) } @{$hold->notes} ] );
2682 # caller is asking for own hold, but may not have permission to view staff notes
2683 unless($e->allowed('VIEW_HOLD')) {
2684 $hold->notes( # filter out any staff notes
2685 [ grep { $U->is_true($_->staff) } @{$hold->notes} ] );
2689 my $user = $hold->usr;
2690 $hold->usr($user->id);
2693 my( $mvr, $volume, $copy, $issuance, $bre ) = find_hold_mvr($e, $hold, $args->{suppress_mvr});
2695 flesh_hold_notices([$hold], $e) unless $args->{suppress_notices};
2696 flesh_hold_transits([$hold]) unless $args->{suppress_transits};
2698 my $details = retrieve_hold_queue_status_impl($e, $hold);
2707 $resp->{mvr} = $mvr unless $args->{suppress_mvr};
2708 unless($args->{suppress_patron_details}) {
2709 my $card = $e->retrieve_actor_card($user->card) or return $e->event;
2710 $resp->{patron_first} = $user->first_given_name,
2711 $resp->{patron_last} = $user->family_name,
2712 $resp->{patron_barcode} = $card->barcode,
2713 $resp->{patron_alias} = $user->alias,
2716 $resp->{bre} = $bre if $args->{include_bre};
2723 # -----------------------------------------------------
2724 # Returns the MVR object that represents what the
2726 # -----------------------------------------------------
2728 my( $e, $hold, $no_mvr ) = @_;
2735 if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2736 my $mr = $e->retrieve_metabib_metarecord($hold->target)
2737 or return $e->event;
2738 $tid = $mr->master_record;
2740 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
2741 $tid = $hold->target;
2743 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2744 $volume = $e->retrieve_asset_call_number($hold->target)
2745 or return $e->event;
2746 $tid = $volume->record;
2748 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2749 $issuance = $e->retrieve_serial_issuance([
2751 {flesh => 1, flesh_fields => {siss => [ qw/subscription/ ]}}
2752 ]) or return $e->event;
2754 $tid = $issuance->subscription->record_entry;
2756 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_COPY ) {
2757 $copy = $e->retrieve_asset_copy([
2759 {flesh => 1, flesh_fields => {acp => ['call_number']}}
2760 ]) or return $e->event;
2762 $volume = $copy->call_number;
2763 $tid = $volume->record;
2766 if(!$copy and ref $hold->current_copy ) {
2767 $copy = $hold->current_copy;
2768 $hold->current_copy($copy->id);
2771 if(!$volume and $copy) {
2772 $volume = $e->retrieve_asset_call_number($copy->call_number);
2775 # TODO return metarcord mvr for M holds
2776 my $title = $e->retrieve_biblio_record_entry($tid);
2777 return ( ($no_mvr) ? undef : $U->record_to_mvr($title), $volume, $copy, $issuance, $title );
2780 __PACKAGE__->register_method(
2781 method => 'clear_shelf_cache',
2782 api_name => 'open-ils.circ.hold.clear_shelf.get_cache',
2786 Returns the holds processed with the given cache key
2791 sub clear_shelf_cache {
2792 my($self, $client, $auth, $cache_key, $chunk_size) = @_;
2793 my $e = new_editor(authtoken => $auth, xact => 1);
2794 return $e->die_event unless $e->checkauth and $e->allowed('VIEW_HOLD');
2797 my $hold_data = OpenSRF::Utils::Cache->new('global')->get_cache($cache_key);
2800 $logger->info("no hold data found in cache"); # XXX TODO return event
2806 foreach (keys %$hold_data) {
2807 $maximum += scalar(@{ $hold_data->{$_} });
2809 $client->respond({"maximum" => $maximum, "progress" => 0});
2811 for my $action (sort keys %$hold_data) {
2812 while (@{$hold_data->{$action}}) {
2813 my @hid_chunk = splice @{$hold_data->{$action}}, 0, $chunk_size;
2815 my $result_chunk = $e->json_query({
2817 "acp" => ["barcode"],
2819 first_given_name second_given_name family_name alias
2829 "field" => "id", "fkey" => "current_copy",
2832 "field" => "id", "fkey" => "call_number",
2835 "field" => "id", "fkey" => "record"
2839 "acpl" => {"field" => "id", "fkey" => "location"}
2842 "au" => {"field" => "id", "fkey" => "usr"}
2845 "where" => {"+ahr" => {"id" => \@hid_chunk}}
2846 }, {"substream" => 1}) or return $e->die_event;
2850 +{"action" => $action, "hold_details" => $_}
2861 __PACKAGE__->register_method(
2862 method => 'clear_shelf_process',
2864 api_name => 'open-ils.circ.hold.clear_shelf.process',
2867 1. Find all holds that have expired on the holds shelf
2869 3. If a clear-shelf status is configured, put targeted copies into this status
2870 4. Divide copies into 3 groups: items to transit, items to reshelve, and items
2871 that are needed for holds. No subsequent action is taken on the holds
2872 or items after grouping.
2877 sub clear_shelf_process {
2878 my($self, $client, $auth, $org_id) = @_;
2880 my $e = new_editor(authtoken=>$auth, xact => 1);
2881 $e->checkauth or return $e->die_event;
2882 my $cache = OpenSRF::Utils::Cache->new('global');
2884 $org_id ||= $e->requestor->ws_ou;
2885 $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
2887 my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
2889 # Find holds on the shelf that have been there too long
2890 my $hold_ids = $e->search_action_hold_request(
2891 { shelf_expire_time => {'<' => 'now'},
2892 pickup_lib => $org_id,
2893 cancel_time => undef,
2894 fulfillment_time => undef,
2895 shelf_time => {'!=' => undef},
2896 capture_time => {'!=' => undef},
2897 current_copy => {'!=' => undef},
2903 my $chunk_size = 25; # chunked status updates
2905 for my $hold_id (@$hold_ids) {
2907 $logger->info("Clear shelf processing hold $hold_id");
2909 my $hold = $e->retrieve_action_hold_request([
2912 flesh_fields => {ahr => ['current_copy']}
2916 $hold->cancel_time('now');
2917 $hold->cancel_cause(2); # Hold Shelf expiration
2918 $e->update_action_hold_request($hold) or return $e->die_event;
2920 my $copy = $hold->current_copy;
2922 if($copy_status or $copy_status == 0) {
2923 # if a clear-shelf copy status is defined, update the copy
2924 $copy->status($copy_status);
2925 $copy->edit_date('now');
2926 $copy->editor($e->requestor->id);
2927 $e->update_asset_copy($copy) or return $e->die_event;
2930 push(@holds, $hold);
2931 $client->respond({maximum => scalar(@holds), progress => $counter}) if ( (++$counter % $chunk_size) == 0);
2942 for my $hold (@holds) {
2944 my $copy = $hold->current_copy;
2945 my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
2949 push(@{$cache_data{hold}}, $hold->id); # copy is needed for a hold
2951 } elsif($copy->circ_lib != $e->requestor->ws_ou) {
2953 push(@{$cache_data{transit}}, $hold->id); # copy needs to transit
2957 push(@{$cache_data{shelf}}, $hold->id); # copy needs to go back to the shelf
2961 my $cache_key = md5_hex(time . $$ . rand());
2962 $logger->info("clear_shelf_cache: storing under $cache_key");
2963 $cache->put_cache($cache_key, \%cache_data, 7200); # TODO: 2 hours. configurable?
2965 # tell the client we're done
2966 $client->respond_complete({cache_key => $cache_key});
2968 # fire off the hold cancelation trigger and wait for response so don't flood the service
2969 $U->create_events_for_hook(
2970 'hold_request.cancel.expire_holds_shelf',
2971 $_, $org_id, undef, undef, 1) for @holds;
2974 # tell the client we're done
2975 $client->respond_complete;
2979 __PACKAGE__->register_method(
2980 method => 'usr_hold_summary',
2981 api_name => 'open-ils.circ.holds.user_summary',
2983 Returns a summary of holds statuses for a given user
2987 sub usr_hold_summary {
2988 my($self, $conn, $auth, $user_id) = @_;
2990 my $e = new_editor(authtoken=>$auth);
2991 $e->checkauth or return $e->event;
2992 $e->allowed('VIEW_HOLD') or return $e->event;
2994 my $holds = $e->search_action_hold_request(
2997 fulfillment_time => undef,
2998 cancel_time => undef,
3002 my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
3003 $summary{_hold_status($e, $_)} += 1 for @$holds;
3009 __PACKAGE__->register_method(
3010 method => 'hold_has_copy_at',
3011 api_name => 'open-ils.circ.hold.has_copy_at',
3014 'Returns the ID of the found copy and name of the shelving location if there is ' .
3015 'an available copy at the specified org unit. Returns empty hash otherwise. ' .
3016 'The anticipated use for this method is to determine whether an item is ' .
3017 'available at the library where the user is placing the hold (or, alternatively, '.
3018 'at the pickup library) to encourage bypassing the hold placement and just ' .
3019 'checking out the item.' ,
3021 { desc => 'Authentication Token', type => 'string' },
3022 { desc => 'Method Arguments. Options include: hold_type, hold_target, org_unit. '
3023 . 'hold_type is the hold type code (T, V, C, M, ...). '
3024 . 'hold_target is the identifier of the hold target object. '
3025 . 'org_unit is org unit ID.',
3030 desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
3036 sub hold_has_copy_at {
3037 my($self, $conn, $auth, $args) = @_;
3039 my $e = new_editor(authtoken=>$auth);
3040 $e->checkauth or return $e->event;
3042 my $hold_type = $$args{hold_type};
3043 my $hold_target = $$args{hold_target};
3044 my $org_unit = $$args{org_unit};
3047 select => {acp => ['id'], acpl => ['name']},
3050 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
3051 ccs => {field => 'id', filter => { holdable => 't'}, fkey => 'status' }
3054 where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit}},
3058 if($hold_type eq 'C') {
3060 $query->{where}->{'+acp'}->{id} = $hold_target;
3062 } elsif($hold_type eq 'V') {
3064 $query->{where}->{'+acp'}->{c