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 $e->update_action_hold_request($hold) or return $e->die_event;
572 $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
578 __PACKAGE__->register_method(
579 method => "cancel_hold",
580 api_name => "open-ils.circ.hold.cancel",
582 desc => 'Cancels the specified hold. The login session is the requestor. If the requestor is different from the usr field ' .
583 'on the hold, the requestor must have CANCEL_HOLDS permissions. The hold may be either the hold object or the hold id',
585 {desc => 'Authentication token', type => 'string'},
586 {desc => 'Hold ID', type => 'number'},
587 {desc => 'Cause of Cancellation', type => 'string'},
588 {desc => 'Note', type => 'string'}
591 desc => '1 on success, event on error'
597 my($self, $client, $auth, $holdid, $cause, $note) = @_;
599 my $e = new_editor(authtoken=>$auth, xact=>1);
600 return $e->die_event unless $e->checkauth;
602 my $hold = $e->retrieve_action_hold_request($holdid)
603 or return $e->die_event;
605 if( $e->requestor->id ne $hold->usr ) {
606 return $e->die_event unless $e->allowed('CANCEL_HOLDS');
609 if ($hold->cancel_time) {
614 # If the hold is captured, reset the copy status
615 if( $hold->capture_time and $hold->current_copy ) {
617 my $copy = $e->retrieve_asset_copy($hold->current_copy)
618 or return $e->die_event;
620 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
621 $logger->info("canceling hold $holdid whose item is on the holds shelf");
622 # $logger->info("setting copy to status 'reshelving' on hold cancel");
623 # $copy->status(OILS_COPY_STATUS_RESHELVING);
624 # $copy->editor($e->requestor->id);
625 # $copy->edit_date('now');
626 # $e->update_asset_copy($copy) or return $e->event;
628 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
631 $logger->warn("! canceling hold [$hid] that is in transit");
632 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
635 my $trans = $e->retrieve_action_transit_copy($transid);
636 # Leave the transit alive, but set the copy status to
637 # reshelving so it will be properly reshelved when it gets back home
639 $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
640 $e->update_action_transit_copy($trans) or return $e->die_event;
646 $hold->cancel_time('now');
647 $hold->cancel_cause($cause);
648 $hold->cancel_note($note);
649 $e->update_action_hold_request($hold)
650 or return $e->die_event;
652 delete_hold_copy_maps($self, $e, $hold->id);
656 $U->create_events_for_hook('hold_request.cancel.staff', $hold, $hold->pickup_lib)
657 if $e->requestor->id != $hold->usr;
662 sub delete_hold_copy_maps {
667 my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
669 $editor->delete_action_hold_copy_map($_)
670 or return $editor->event;
676 my $update_hold_desc = 'The login session is the requestor. ' .
677 'If the requestor is different from the usr field on the hold, ' .
678 'the requestor must have UPDATE_HOLDS permissions. ' .
679 'If supplying a hash of hold data, "id" must be included. ' .
680 'The hash is ignored if a hold object is supplied, ' .
681 'so you should supply only one kind of hold data argument.' ;
683 __PACKAGE__->register_method(
684 method => "update_hold",
685 api_name => "open-ils.circ.hold.update",
687 desc => "Updates the specified hold. $update_hold_desc",
689 {desc => 'Authentication token', type => 'string'},
690 {desc => 'Hold Object', type => 'object'},
691 {desc => 'Hash of values to be applied', type => 'object'}
694 desc => 'Hold ID on success, event on error',
700 __PACKAGE__->register_method(
701 method => "batch_update_hold",
702 api_name => "open-ils.circ.hold.update.batch",
705 desc => "Updates the specified hold(s). $update_hold_desc",
707 {desc => 'Authentication token', type => 'string'},
708 {desc => 'Array of hold obejcts', type => 'array' },
709 {desc => 'Array of hashes of values to be applied', type => 'array' }
712 desc => 'Hold ID per success, event per error',
718 my($self, $client, $auth, $hold, $values) = @_;
719 my $e = new_editor(authtoken=>$auth, xact=>1);
720 return $e->die_event unless $e->checkauth;
721 my $resp = update_hold_impl($self, $e, $hold, $values);
722 if ($U->event_code($resp)) {
726 $e->commit; # FIXME: update_hold_impl already does $e->commit ??
730 sub batch_update_hold {
731 my($self, $client, $auth, $hold_list, $values_list) = @_;
732 my $e = new_editor(authtoken=>$auth);
733 return $e->die_event unless $e->checkauth;
735 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.
737 $values_list ||= []; # FIXME: either move this above $count declaration, or send an event if both lists undef. Probably the latter.
739 # FIXME: Failing over to [] guarantees warnings for "Use of unitialized value" in update_hold_impl call.
740 # FIXME: We should be sure we only call update_hold_impl with hold object OR hash, not both.
742 for my $idx (0..$count-1) {
744 my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
745 $e->xact_commit unless $U->event_code($resp);
746 $client->respond($resp);
750 return undef; # not in the register return type, assuming we should always have at least one list populated
753 sub update_hold_impl {
754 my($self, $e, $hold, $values) = @_;
757 $hold = $e->retrieve_action_hold_request($values->{id})
758 or return $e->die_event;
759 for my $k (keys %$values) {
760 if (defined $values->{$k}) {
761 $hold->$k($values->{$k});
763 my $f = "clear_$k"; $hold->$f();
768 my $orig_hold = $e->retrieve_action_hold_request($hold->id)
769 or return $e->die_event;
771 # don't allow the user to be changed
772 return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
774 if($hold->usr ne $e->requestor->id) {
775 # if the hold is for a different user, make sure the
776 # requestor has the appropriate permissions
777 my $usr = $e->retrieve_actor_user($hold->usr)
778 or return $e->die_event;
779 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
783 # --------------------------------------------------------------
784 # Changing the request time is like playing God
785 # --------------------------------------------------------------
786 if($hold->request_time ne $orig_hold->request_time) {
787 return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
788 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
791 # --------------------------------------------------------------
792 # if the hold is on the holds shelf or in transit and the pickup
793 # lib changes we need to create a new transit.
794 # --------------------------------------------------------------
795 if($orig_hold->pickup_lib ne $hold->pickup_lib) {
797 my $status = _hold_status($e, $hold);
799 if($status == 3) { # in transit
801 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
802 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
804 $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
806 # update the transit to reflect the new pickup location
807 my $transit = $e->search_action_hold_transit_copy(
808 {hold=>$hold->id, dest_recv_time => undef})->[0]
809 or return $e->die_event;
811 $transit->prev_dest($transit->dest); # mark the previous destination on the transit
812 $transit->dest($hold->pickup_lib);
813 $e->update_action_hold_transit_copy($transit) or return $e->die_event;
815 } elsif($status == 4) { # on holds shelf
817 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
818 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
820 $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
822 # create the new transit
823 my $evt = transit_hold($e, $orig_hold, $hold, $e->retrieve_asset_copy($hold->current_copy));
828 update_hold_if_frozen($self, $e, $hold, $orig_hold);
829 $e->update_action_hold_request($hold) or return $e->die_event;
832 # a change to mint-condition changes the set of potential copies, so retarget the hold;
833 if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
834 _reset_hold($self, $e->requestor, $hold)
841 my($e, $orig_hold, $hold, $copy) = @_;
842 my $src = $orig_hold->pickup_lib;
843 my $dest = $hold->pickup_lib;
845 $logger->info("putting hold into transit on pickup_lib update");
847 my $transit = Fieldmapper::action::hold_transit_copy->new;
848 $transit->hold($hold->id);
849 $transit->source($src);
850 $transit->dest($dest);
851 $transit->target_copy($copy->id);
852 $transit->source_send_time('now');
853 $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
855 $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
856 $copy->editor($e->requestor->id);
857 $copy->edit_date('now');
859 $e->create_action_hold_transit_copy($transit) or return $e->die_event;
860 $e->update_asset_copy($copy) or return $e->die_event;
864 # if the hold is frozen, this method ensures that the hold is not "targeted",
865 # that is, it clears the current_copy and prev_check_time to essentiallly
866 # reset the hold. If it is being activated, it runs the targeter in the background
867 sub update_hold_if_frozen {
868 my($self, $e, $hold, $orig_hold) = @_;
869 return if $hold->capture_time;
871 if($U->is_true($hold->frozen)) {
872 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
873 $hold->clear_current_copy;
874 $hold->clear_prev_check_time;
877 if($U->is_true($orig_hold->frozen)) {
878 $logger->info("Running targeter on activated hold ".$hold->id);
879 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
884 __PACKAGE__->register_method(
885 method => "hold_note_CUD",
886 api_name => "open-ils.circ.hold_request.note.cud",
888 desc => 'Create, update or delete a hold request note. If the operator (from Auth. token) '
889 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
891 { desc => 'Authentication token', type => 'string' },
892 { desc => 'Hold note object', type => 'object' }
895 desc => 'Returns the note ID, event on error'
901 my($self, $conn, $auth, $note) = @_;
903 my $e = new_editor(authtoken => $auth, xact => 1);
904 return $e->die_event unless $e->checkauth;
906 my $hold = $e->retrieve_action_hold_request($note->hold)
907 or return $e->die_event;
909 if($hold->usr ne $e->requestor->id) {
910 my $usr = $e->retrieve_actor_user($hold->usr);
911 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
912 $note->staff('t') if $note->isnew;
916 $e->create_action_hold_request_note($note) or return $e->die_event;
917 } elsif($note->ischanged) {
918 $e->update_action_hold_request_note($note) or return $e->die_event;
919 } elsif($note->isdeleted) {
920 $e->delete_action_hold_request_note($note) or return $e->die_event;
928 __PACKAGE__->register_method(
929 method => "retrieve_hold_status",
930 api_name => "open-ils.circ.hold.status.retrieve",
932 desc => 'Calculates the current status of the hold. The requestor must have ' .
933 'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
935 { desc => 'Hold ID', type => 'number' }
938 # type => 'number', # event sometimes
939 desc => <<'END_OF_DESC'
940 Returns event on error or:
941 -1 on error (for now),
942 1 for 'waiting for copy to become available',
943 2 for 'waiting for copy capture',
946 5 for 'hold-shelf-delay'
953 sub retrieve_hold_status {
954 my($self, $client, $auth, $hold_id) = @_;
956 my $e = new_editor(authtoken => $auth);
957 return $e->event unless $e->checkauth;
958 my $hold = $e->retrieve_action_hold_request($hold_id)
961 if( $e->requestor->id != $hold->usr ) {
962 return $e->event unless $e->allowed('VIEW_HOLD');
965 return _hold_status($e, $hold);
971 if ($hold->cancel_time) {
974 return 1 unless $hold->current_copy;
975 return 2 unless $hold->capture_time;
977 my $copy = $hold->current_copy;
978 unless( ref $copy ) {
979 $copy = $e->retrieve_asset_copy($hold->current_copy)
983 return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
985 if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
987 my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
988 return 4 unless $hs_wait_interval;
990 # if a hold_shelf_status_delay interval is defined and start_time plus
991 # the interval is greater than now, consider the hold to be in the virtual
992 # "on its way to the holds shelf" status. Return 5.
994 my $transit = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
995 my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
996 $start_time = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
997 my $end_time = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
999 return 5 if $end_time > DateTime->now;
1008 __PACKAGE__->register_method(
1009 method => "retrieve_hold_queue_stats",
1010 api_name => "open-ils.circ.hold.queue_stats.retrieve",
1012 desc => 'Returns summary data about the state of a hold',
1014 { desc => 'Authentication token', type => 'string'},
1015 { desc => 'Hold ID', type => 'number'},
1018 desc => q/Summary object with keys:
1019 total_holds : total holds in queue
1020 queue_position : current queue position
1021 potential_copies : number of potential copies for this hold
1022 estimated_wait : estimated wait time in days
1023 status : hold status
1024 -1 => error or unexpected state,
1025 1 => 'waiting for copy to become available',
1026 2 => 'waiting for copy capture',
1029 5 => 'hold-shelf-delay'
1036 sub retrieve_hold_queue_stats {
1037 my($self, $conn, $auth, $hold_id) = @_;
1038 my $e = new_editor(authtoken => $auth);
1039 return $e->event unless $e->checkauth;
1040 my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1041 if($e->requestor->id != $hold->usr) {
1042 return $e->event unless $e->allowed('VIEW_HOLD');
1044 return retrieve_hold_queue_status_impl($e, $hold);
1047 sub retrieve_hold_queue_status_impl {
1051 # The holds queue is defined as the distinct set of holds that share at
1052 # least one potential copy with the context hold, plus any holds that
1053 # share the same hold type and target. The latter part exists to
1054 # accomodate holds that currently have no potential copies
1055 my $q_holds = $e->json_query({
1057 # fetch cut_in_line and request_time since they're in the order_by
1058 # and we're asking for distinct values
1059 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1060 from => { ahr => 'ahcm' },
1064 "field" => "cut_in_line",
1065 "transform" => "coalesce",
1067 "direction" => "desc"
1069 { "class" => "ahr", "field" => "request_time" }
1076 select => {ahcm => ['target_copy']},
1078 where => {hold => $hold->id}
1085 if (!@$q_holds) { # none? maybe we don't have a map ...
1086 $q_holds = $e->json_query({
1087 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1092 "field" => "cut_in_line",
1093 "transform" => "coalesce",
1095 "direction" => "desc"
1097 { "class" => "ahr", "field" => "request_time" }
1100 hold_type => $hold->hold_type,
1101 target => $hold->target
1108 for my $h (@$q_holds) {
1109 last if $h->{id} == $hold->id;
1113 my $hold_data = $e->json_query({
1115 acp => [ {column => 'id', transform => 'count', aggregate => 1, alias => 'count'} ],
1116 ccm => [ {column =>'avg_wait_time'} ]
1122 ccm => {type => 'left'}
1127 where => {'+ahcm' => {hold => $hold->id} }
1130 my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1132 my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1133 my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1134 $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1135 $default_wait ||= '0 seconds';
1137 # Estimated wait time is the average wait time across the set
1138 # of potential copies, divided by the number of potential copies
1139 # times the queue position.
1141 my $combined_secs = 0;
1142 my $num_potentials = 0;
1144 for my $wait_data (@$hold_data) {
1145 my $count += $wait_data->{count};
1146 $combined_secs += $count *
1147 OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1148 $num_potentials += $count;
1151 my $estimated_wait = -1;
1153 if($num_potentials) {
1154 my $avg_wait = $combined_secs / $num_potentials;
1155 $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1156 $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1160 total_holds => scalar(@$q_holds),
1161 queue_position => $qpos,
1162 potential_copies => $num_potentials,
1163 status => _hold_status( $e, $hold ),
1164 estimated_wait => int($estimated_wait)
1169 sub fetch_open_hold_by_current_copy {
1172 my $hold = $apputils->simplereq(
1174 'open-ils.cstore.direct.action.hold_request.search.atomic',
1175 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1176 return $hold->[0] if ref($hold);
1180 sub fetch_related_holds {
1183 return $apputils->simplereq(
1185 'open-ils.cstore.direct.action.hold_request.search.atomic',
1186 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1190 __PACKAGE__->register_method(
1191 method => "hold_pull_list",
1192 api_name => "open-ils.circ.hold_pull_list.retrieve",
1194 desc => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1195 'The location is determined by the login session.',
1197 { desc => 'Limit (optional)', type => 'number'},
1198 { desc => 'Offset (optional)', type => 'number'},
1201 desc => 'reference to a list of holds, or event on failure',
1206 __PACKAGE__->register_method(
1207 method => "hold_pull_list",
1208 api_name => "open-ils.circ.hold_pull_list.id_list.retrieve",
1210 desc => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1211 'The location is determined by the login session.',
1213 { desc => 'Limit (optional)', type => 'number'},
1214 { desc => 'Offset (optional)', type => 'number'},
1217 desc => 'reference to a list of holds, or event on failure',
1222 __PACKAGE__->register_method(
1223 method => "hold_pull_list",
1224 api_name => "open-ils.circ.hold_pull_list.retrieve.count",
1226 desc => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1227 'The location is determined by the login session.',
1229 { desc => 'Limit (optional)', type => 'number'},
1230 { desc => 'Offset (optional)', type => 'number'},
1233 desc => 'Holds count (integer), or event on failure',
1240 sub hold_pull_list {
1241 my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1242 my( $reqr, $evt ) = $U->checkses($authtoken);
1243 return $evt if $evt;
1245 my $org = $reqr->ws_ou || $reqr->home_ou;
1246 # the perm locaiton shouldn't really matter here since holds
1247 # will exist all over and VIEW_HOLDS should be universal
1248 $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1249 return $evt if $evt;
1251 if($self->api_name =~ /count/) {
1253 my $count = $U->storagereq(
1254 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1255 $org, $limit, $offset );
1257 $logger->info("Grabbing pull list for org unit $org with $count items");
1260 } elsif( $self->api_name =~ /id_list/ ) {
1261 return $U->storagereq(
1262 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1263 $org, $limit, $offset );
1266 return $U->storagereq(
1267 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1268 $org, $limit, $offset );
1272 __PACKAGE__->register_method(
1273 method => "print_hold_pull_list",
1274 api_name => "open-ils.circ.hold_pull_list.print",
1276 desc => 'Returns an HTML-formatted holds pull list',
1278 { desc => 'Authtoken', type => 'string'},
1279 { desc => 'Org unit ID. Optional, defaults to workstation org unit', type => 'number'},
1282 desc => 'HTML string',
1288 sub print_hold_pull_list {
1289 my($self, $client, $auth, $org_id) = @_;
1291 my $e = new_editor(authtoken=>$auth);
1292 return $e->event unless $e->checkauth;
1294 $org_id = (defined $org_id) ? $org_id : $e->requestor->ws_ou;
1295 return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1297 my $hold_ids = $U->storagereq(
1298 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1301 return undef unless @$hold_ids;
1303 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1305 # Holds will /NOT/ be in order after this ...
1306 my $holds = $e->search_action_hold_request({id => $hold_ids}, {substream => 1});
1307 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1309 # ... so we must resort.
1310 my $hold_map = +{map { $_->id => $_ } @$holds};
1311 my $sorted_holds = [];
1312 push @$sorted_holds, $hold_map->{$_} foreach @$hold_ids;
1314 return $U->fire_object_event(
1315 undef, "ahr.format.pull_list", $sorted_holds,
1316 $org_id, undef, undef, $client
1321 __PACKAGE__->register_method(
1322 method => "print_hold_pull_list_stream",
1324 api_name => "open-ils.circ.hold_pull_list.print.stream",
1326 desc => 'Returns a stream of fleshed holds',
1328 { desc => 'Authtoken', type => 'string'},
1329 { desc => 'Hash of optional param: Org unit ID (defaults to workstation org unit), limit, offset, sort (array of: acplo.position, call_number, request_time)',
1334 desc => 'A stream of fleshed holds',
1340 sub print_hold_pull_list_stream {
1341 my($self, $client, $auth, $params) = @_;
1343 my $e = new_editor(authtoken=>$auth);
1344 return $e->die_event unless $e->checkauth;
1346 delete($$params{org_id}) unless (int($$params{org_id}));
1347 delete($$params{limit}) unless (int($$params{limit}));
1348 delete($$params{offset}) unless (int($$params{offset}));
1349 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1350 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1351 $$params{chunk_size} ||= 10;
1353 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1354 return $e->die_event unless $e->allowed('VIEW_HOLD', $$params{org_id });
1357 if ($$params{sort} && @{ $$params{sort} }) {
1358 for my $s (@{ $$params{sort} }) {
1359 if ($s eq 'acplo.position') {
1361 "class" => "acplo", "field" => "position",
1362 "transform" => "coalesce", "params" => [999]
1364 } elsif ($s eq 'call_number') {
1365 push @$sort, {"class" => "acn", "field" => "label"};
1366 } elsif ($s eq 'request_time') {
1367 push @$sort, {"class" => "ahr", "field" => "request_time"};
1371 push @$sort, {"class" => "ahr", "field" => "request_time"};
1374 my $holds_ids = $e->json_query(
1376 "select" => {"ahr" => ["id"]},
1381 "fkey" => "current_copy",
1383 "circ_lib" => $$params{org_id}, "status" => [0,7]
1388 "fkey" => "call_number"
1392 "fkey" => "circ_lib",
1395 "location" => {"=" => {"+acp" => "location"}}
1404 "capture_time" => undef,
1405 "cancel_time" => undef,
1407 {"expire_time" => undef },
1408 {"expire_time" => {">" => "now"}}
1412 (@$sort ? (order_by => $sort) : ()),
1413 ($$params{limit} ? (limit => $$params{limit}) : ()),
1414 ($$params{offset} ? (offset => $$params{offset}) : ())
1415 }, {"substream" => 1}
1416 ) or return $e->die_event;
1418 $logger->info("about to stream back " . scalar(@$holds_ids) . " holds");
1421 for my $hid (@$holds_ids) {
1422 push @chunk, $e->retrieve_action_hold_request([
1426 "ahr" => ["usr", "current_copy"],
1428 "acp" => ["location", "call_number"],
1434 if (@chunk >= $$params{chunk_size}) {
1435 $client->respond( \@chunk );
1439 $client->respond_complete( \@chunk ) if (@chunk);
1446 __PACKAGE__->register_method(
1447 method => 'fetch_hold_notify',
1448 api_name => 'open-ils.circ.hold_notification.retrieve_by_hold',
1451 Returns a list of hold notification objects based on hold id.
1452 @param authtoken The loggin session key
1453 @param holdid The id of the hold whose notifications we want to retrieve
1454 @return An array of hold notification objects, event on error.
1458 sub fetch_hold_notify {
1459 my( $self, $conn, $authtoken, $holdid ) = @_;
1460 my( $requestor, $evt ) = $U->checkses($authtoken);
1461 return $evt if $evt;
1462 my ($hold, $patron);
1463 ($hold, $evt) = $U->fetch_hold($holdid);
1464 return $evt if $evt;
1465 ($patron, $evt) = $U->fetch_user($hold->usr);
1466 return $evt if $evt;
1468 $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1469 return $evt if $evt;
1471 $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1472 return $U->cstorereq(
1473 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1477 __PACKAGE__->register_method(
1478 method => 'create_hold_notify',
1479 api_name => 'open-ils.circ.hold_notification.create',
1481 Creates a new hold notification object
1482 @param authtoken The login session key
1483 @param notification The hold notification object to create
1484 @return ID of the new object on success, Event on error
1488 sub create_hold_notify {
1489 my( $self, $conn, $auth, $note ) = @_;
1490 my $e = new_editor(authtoken=>$auth, xact=>1);
1491 return $e->die_event unless $e->checkauth;
1493 my $hold = $e->retrieve_action_hold_request($note->hold)
1494 or return $e->die_event;
1495 my $patron = $e->retrieve_actor_user($hold->usr)
1496 or return $e->die_event;
1498 return $e->die_event unless
1499 $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1501 $note->notify_staff($e->requestor->id);
1502 $e->create_action_hold_notification($note) or return $e->die_event;
1507 __PACKAGE__->register_method(
1508 method => 'create_hold_note',
1509 api_name => 'open-ils.circ.hold_note.create',
1511 Creates a new hold request note object
1512 @param authtoken The login session key
1513 @param note The hold note object to create
1514 @return ID of the new object on success, Event on error
1518 sub create_hold_note {
1519 my( $self, $conn, $auth, $note ) = @_;
1520 my $e = new_editor(authtoken=>$auth, xact=>1);
1521 return $e->die_event unless $e->checkauth;
1523 my $hold = $e->retrieve_action_hold_request($note->hold)
1524 or return $e->die_event;
1525 my $patron = $e->retrieve_actor_user($hold->usr)
1526 or return $e->die_event;
1528 return $e->die_event unless
1529 $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn. Probably want something more specific
1531 $e->create_action_hold_request_note($note) or return $e->die_event;
1536 __PACKAGE__->register_method(
1537 method => 'reset_hold',
1538 api_name => 'open-ils.circ.hold.reset',
1540 Un-captures and un-targets a hold, essentially returning
1541 it to the state it was in directly after it was placed,
1542 then attempts to re-target the hold
1543 @param authtoken The login session key
1544 @param holdid The id of the hold
1550 my( $self, $conn, $auth, $holdid ) = @_;
1552 my ($hold, $evt) = $U->fetch_hold($holdid);
1553 return $evt if $evt;
1554 ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1555 return $evt if $evt;
1556 $evt = _reset_hold($self, $reqr, $hold);
1557 return $evt if $evt;
1562 __PACKAGE__->register_method(
1563 method => 'reset_hold_batch',
1564 api_name => 'open-ils.circ.hold.reset.batch'
1567 sub reset_hold_batch {
1568 my($self, $conn, $auth, $hold_ids) = @_;
1570 my $e = new_editor(authtoken => $auth);
1571 return $e->event unless $e->checkauth;
1573 for my $hold_id ($hold_ids) {
1575 my $hold = $e->retrieve_action_hold_request(
1576 [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}])
1577 or return $e->event;
1579 next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1580 _reset_hold($self, $e->requestor, $hold);
1588 my ($self, $reqr, $hold) = @_;
1590 my $e = new_editor(xact =>1, requestor => $reqr);
1592 $logger->info("reseting hold ".$hold->id);
1594 my $hid = $hold->id;
1596 if( $hold->capture_time and $hold->current_copy ) {
1598 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1599 or return $e->die_event;
1601 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1602 $logger->info("setting copy to status 'reshelving' on hold retarget");
1603 $copy->status(OILS_COPY_STATUS_RESHELVING);
1604 $copy->editor($e->requestor->id);
1605 $copy->edit_date('now');
1606 $e->update_asset_copy($copy) or return $e->die_event;
1608 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1610 # We don't want the copy to remain "in transit"
1611 $copy->status(OILS_COPY_STATUS_RESHELVING);
1612 $logger->warn("! reseting hold [$hid] that is in transit");
1613 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1616 my $trans = $e->retrieve_action_transit_copy($transid);
1618 $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1619 my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1);
1620 $logger->info("Transit abort completed with result $evt");
1621 unless ("$evt" eq 1) {
1630 $hold->clear_capture_time;
1631 $hold->clear_current_copy;
1632 $hold->clear_shelf_time;
1633 $hold->clear_shelf_expire_time;
1635 $e->update_action_hold_request($hold) or return $e->die_event;
1639 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1645 __PACKAGE__->register_method(
1646 method => 'fetch_open_title_holds',
1647 api_name => 'open-ils.circ.open_holds.retrieve',
1649 Returns a list ids of un-fulfilled holds for a given title id
1650 @param authtoken The login session key
1651 @param id the id of the item whose holds we want to retrieve
1652 @param type The hold type - M, T, I, V, C, F, R
1656 sub fetch_open_title_holds {
1657 my( $self, $conn, $auth, $id, $type, $org ) = @_;
1658 my $e = new_editor( authtoken => $auth );
1659 return $e->event unless $e->checkauth;
1662 $org ||= $e->requestor->ws_ou;
1664 # return $e->search_action_hold_request(
1665 # { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1667 # XXX make me return IDs in the future ^--
1668 my $holds = $e->search_action_hold_request(
1671 cancel_time => undef,
1673 fulfillment_time => undef
1677 flesh_hold_transits($holds);
1682 sub flesh_hold_transits {
1684 for my $hold ( @$holds ) {
1686 $apputils->simplereq(
1688 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1689 { hold => $hold->id },
1690 { order_by => { ahtc => 'id desc' }, limit => 1 }
1696 sub flesh_hold_notices {
1697 my( $holds, $e ) = @_;
1698 $e ||= new_editor();
1700 for my $hold (@$holds) {
1701 my $notices = $e->search_action_hold_notification(
1703 { hold => $hold->id },
1704 { order_by => { anh => 'notify_time desc' } },
1709 $hold->notify_count(scalar(@$notices));
1711 my $n = $e->retrieve_action_hold_notification($$notices[0])
1712 or return $e->event;
1713 $hold->notify_time($n->notify_time);
1719 __PACKAGE__->register_method(
1720 method => 'fetch_captured_holds',
1721 api_name => 'open-ils.circ.captured_holds.on_shelf.retrieve',
1724 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
1725 @param authtoken The login session key
1726 @param org The org id of the location in question
1730 __PACKAGE__->register_method(
1731 method => 'fetch_captured_holds',
1732 api_name => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
1735 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
1736 @param authtoken The login session key
1737 @param org The org id of the location in question
1741 __PACKAGE__->register_method(
1742 method => 'fetch_captured_holds',
1743 api_name => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
1746 Returns list ids of shelf-expired un-fulfilled holds for a given title id
1747 @param authtoken The login session key
1748 @param org The org id of the location in question
1753 sub fetch_captured_holds {
1754 my( $self, $conn, $auth, $org ) = @_;
1756 my $e = new_editor(authtoken => $auth);
1757 return $e->die_event unless $e->checkauth;
1758 return $e->die_event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
1760 $org ||= $e->requestor->ws_ou;
1763 select => { ahr => ['id'] },
1768 fkey => 'current_copy'
1773 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
1775 capture_time => { "!=" => undef },
1776 current_copy => { "!=" => undef },
1777 fulfillment_time => undef,
1779 cancel_time => undef,
1783 if($self->api_name =~ /expired/) {
1784 $query->{'where'}->{'+ahr'}->{'shelf_expire_time'} = {'<' => 'now'};
1785 $query->{'where'}->{'+ahr'}->{'shelf_time'} = {'!=' => undef};
1787 my $hold_ids = $e->json_query( $query );
1789 for my $hold_id (@$hold_ids) {
1790 if($self->api_name =~ /id_list/) {
1791 $conn->respond($hold_id->{id});
1795 $e->retrieve_action_hold_request([
1799 flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
1800 order_by => {anh => 'notify_time desc'}
1810 __PACKAGE__->register_method(
1811 method => "print_expired_holds_stream",
1812 api_name => "open-ils.circ.captured_holds.expired.print.stream",
1816 sub print_expired_holds_stream {
1817 my ($self, $client, $auth, $params) = @_;
1819 # No need to check specific permissions: we're going to call another method
1820 # that will do that.
1821 my $e = new_editor("authtoken" => $auth);
1822 return $e->die_event unless $e->checkauth;
1824 delete($$params{org_id}) unless (int($$params{org_id}));
1825 delete($$params{limit}) unless (int($$params{limit}));
1826 delete($$params{offset}) unless (int($$params{offset}));
1827 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1828 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1829 $$params{chunk_size} ||= 10;
1831 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1833 my @hold_ids = $self->method_lookup(
1834 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
1835 )->run($auth, $params->{"org_id"});
1840 } elsif (defined $U->event_code($hold_ids[0])) {
1842 return $hold_ids[0];
1845 $logger->info("about to stream back up to " . scalar(@hold_ids) . " expired holds");
1848 my @hid_chunk = splice @hold_ids, 0, $params->{"chunk_size"};
1850 my $result_chunk = $e->json_query({
1852 "acp" => ["barcode"],
1854 first_given_name second_given_name family_name alias
1863 "field" => "id", "fkey" => "current_copy",
1866 "field" => "id", "fkey" => "call_number",
1869 "field" => "id", "fkey" => "record"
1873 "acpl" => {"field" => "id", "fkey" => "location"}
1876 "au" => {"field" => "id", "fkey" => "usr"}
1879 "where" => {"+ahr" => {"id" => \@hid_chunk}}
1880 }) or return $e->die_event;
1881 $client->respond($result_chunk);
1888 __PACKAGE__->register_method(
1889 method => "check_title_hold_batch",
1890 api_name => "open-ils.circ.title_hold.is_possible.batch",
1893 desc => '@see open-ils.circ.title_hold.is_possible.batch',
1895 { desc => 'Authentication token', type => 'string'},
1896 { desc => 'Array of Hash of named parameters', type => 'array'},
1899 desc => 'Array of response objects',
1905 sub check_title_hold_batch {
1906 my($self, $client, $authtoken, $param_list) = @_;
1907 foreach (@$param_list) {
1908 my ($res) = $self->method_lookup('open-ils.circ.title_hold.is_possible')->run($authtoken, $_);
1909 $client->respond($res);
1915 __PACKAGE__->register_method(
1916 method => "check_title_hold",
1917 api_name => "open-ils.circ.title_hold.is_possible",
1919 desc => 'Determines if a hold were to be placed by a given user, ' .
1920 'whether or not said hold would have any potential copies to fulfill it.' .
1921 'The named paramaters of the second argument include: ' .
1922 'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
1923 'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' ,
1925 { desc => 'Authentication token', type => 'string'},
1926 { desc => 'Hash of named parameters', type => 'object'},
1929 desc => 'List of new message IDs (empty if none)',
1935 =head3 check_title_hold (token, hash)
1937 The named fields in the hash are:
1939 patronid - ID of the hold recipient (required)
1940 depth - hold range depth (default 0)
1941 pickup_lib - destination for hold, fallback value for selection_ou
1942 selection_ou - ID of org_unit establishing hard and soft hold boundary settings
1943 issuanceid - ID of the issuance to be held, required for Issuance level hold
1944 titleid - ID (BRN) of the title to be held, required for Title level hold
1945 volume_id - required for Volume level hold
1946 copy_id - required for Copy level hold
1947 mrid - required for Meta-record level hold
1948 hold_type - T, C (or R or F), I, V or M for Title, Copy, Issuance, Volume or Meta-record (default "T")
1950 All key/value pairs are passed on to do_possibility_checks.
1954 # FIXME: better params checking. what other params are required, if any?
1955 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
1956 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still
1957 # used in conditionals, where it may be undefined, causing a warning.
1958 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
1960 sub check_title_hold {
1961 my( $self, $client, $authtoken, $params ) = @_;
1962 my $e = new_editor(authtoken=>$authtoken);
1963 return $e->event unless $e->checkauth;
1965 my %params = %$params;
1966 my $depth = $params{depth} || 0;
1967 my $selection_ou = $params{selection_ou} || $params{pickup_lib};
1969 my $patron = $e->retrieve_actor_user($params{patronid})
1970 or return $e->event;
1972 if( $e->requestor->id ne $patron->id ) {
1973 return $e->event unless
1974 $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
1977 return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
1979 my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
1980 or return $e->event;
1982 my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
1983 my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
1986 my $return_depth = $hard_boundary; # default depth to return on success
1987 if(defined $soft_boundary and $depth < $soft_boundary) {
1988 # work up the tree and as soon as we find a potential copy, use that depth
1989 # also, make sure we don't go past the hard boundary if it exists
1991 # our min boundary is the greater of user-specified boundary or hard boundary
1992 my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?
1993 $hard_boundary : $depth;
1995 my $depth = $soft_boundary;
1996 while($depth >= $min_depth) {
1997 $logger->info("performing hold possibility check with soft boundary $depth");
1998 @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
2000 $return_depth = $depth;
2005 } elsif(defined $hard_boundary and $depth < $hard_boundary) {
2006 # there is no soft boundary, enforce the hard boundary if it exists
2007 $logger->info("performing hold possibility check with hard boundary $hard_boundary");
2008 @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
2010 # no boundaries defined, fall back to user specifed boundary or no boundary
2011 $logger->info("performing hold possibility check with no boundary");
2012 @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
2018 "depth" => $return_depth,
2019 "local_avail" => $status[1]
2021 } elsif ($status[2]) {
2022 my $n = scalar @{$status[2]};
2023 return {"success" => 0, "last_event" => $status[2]->[$n - 1]};
2025 return {"success" => 0};
2031 sub do_possibility_checks {
2032 my($e, $patron, $request_lib, $depth, %params) = @_;
2034 my $issuanceid = $params{issuanceid} || "";
2035 my $titleid = $params{titleid} || "";
2036 my $volid = $params{volume_id};
2037 my $copyid = $params{copy_id};
2038 my $mrid = $params{mrid} || "";
2039 my $pickup_lib = $params{pickup_lib};
2040 my $hold_type = $params{hold_type} || 'T';
2041 my $selection_ou = $params{selection_ou} || $pickup_lib;
2048 if( $hold_type eq OILS_HOLD_TYPE_FORCE || $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_COPY ) {
2050 return $e->event unless $copy = $e->retrieve_asset_copy($copyid);
2051 return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
2052 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2054 return verify_copy_for_hold(
2055 $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib
2058 } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2060 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
2061 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2063 return _check_volume_hold_is_possible(
2064 $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2067 } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
2069 return _check_title_hold_is_possible(
2070 $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2073 } elsif( $hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2075 return _check_issuance_hold_is_possible(
2076 $issuanceid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2079 } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2081 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
2082 my @recs = map { $_->source } @$maps;
2084 for my $rec (@recs) {
2085 @status = _check_title_hold_is_possible(
2086 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2092 # else { Unrecognized hold_type ! } # FIXME: return error? or 0?
2096 sub create_ranged_org_filter {
2097 my($e, $selection_ou, $depth) = @_;
2099 # find the orgs from which this hold may be fulfilled,
2100 # based on the selection_ou and depth
2102 my $top_org = $e->search_actor_org_unit([
2103 {parent_ou => undef},
2104 {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
2107 return () if $depth == $top_org->ou_type->depth;
2109 my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
2110 %org_filter = (circ_lib => []);
2111 push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
2113 $logger->info("hold org filter at depth $depth and selection_ou ".
2114 "$selection_ou created list of @{$org_filter{circ_lib}}");
2120 sub _check_title_hold_is_possible {
2121 my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2123 my $e = new_editor();
2124 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2126 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2127 my $copies = $e->json_query(
2129 select => { acp => ['id', 'circ_lib'] },
2134 fkey => 'call_number',
2138 filter => { id => $titleid },
2143 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2144 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2148 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2153 $logger->info("title possible found ".scalar(@$copies)." potential copies");
2157 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2158 "payload" => {"fail_part" => "no_ultimate_items"}
2163 # -----------------------------------------------------------------------
2164 # sort the copies into buckets based on their circ_lib proximity to
2165 # the patron's home_ou.
2166 # -----------------------------------------------------------------------
2168 my $home_org = $patron->home_ou;
2169 my $req_org = $request_lib->id;
2171 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2173 $prox_cache{$home_org} =
2174 $e->search_actor_org_unit_proximity({from_org => $home_org})
2175 unless $prox_cache{$home_org};
2176 my $home_prox = $prox_cache{$home_org};
2179 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2180 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2182 my @keys = sort { $a <=> $b } keys %buckets;
2185 if( $home_org ne $req_org ) {
2186 # -----------------------------------------------------------------------
2187 # shove the copies close to the request_lib into the primary buckets
2188 # directly before the farthest away copies. That way, they are not
2189 # given priority, but they are checked before the farthest copies.
2190 # -----------------------------------------------------------------------
2191 $prox_cache{$req_org} =
2192 $e->search_actor_org_unit_proximity({from_org => $req_org})
2193 unless $prox_cache{$req_org};
2194 my $req_prox = $prox_cache{$req_org};
2197 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2198 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2200 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2201 my $new_key = $highest_key - 0.5; # right before the farthest prox
2202 my @keys2 = sort { $a <=> $b } keys %buckets2;
2203 for my $key (@keys2) {
2204 last if $key >= $highest_key;
2205 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2209 @keys = sort { $a <=> $b } keys %buckets;
2214 OUTER: for my $key (@keys) {
2215 my @cps = @{$buckets{$key}};
2217 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2219 for my $copyid (@cps) {
2221 next if $seen{$copyid};
2222 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2223 my $copy = $e->retrieve_asset_copy($copyid);
2224 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2226 unless($title) { # grab the title if we don't already have it
2227 my $vol = $e->retrieve_asset_call_number(
2228 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2229 $title = $vol->record;
2232 @status = verify_copy_for_hold(
2233 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2235 last OUTER if $status[0];
2242 sub _check_issuance_hold_is_possible {
2243 my( $issuanceid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2245 my $e = new_editor();
2246 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2248 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2249 my $copies = $e->json_query(
2251 select => { acp => ['id', 'circ_lib'] },
2257 filter => { issuance => $issuanceid }
2259 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2260 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2264 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2270 $logger->info("issuance possible found ".scalar(@$copies)." potential copies");
2274 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2275 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2280 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2281 "payload" => {"fail_part" => "no_ultimate_items"}
2289 # -----------------------------------------------------------------------
2290 # sort the copies into buckets based on their circ_lib proximity to
2291 # the patron's home_ou.
2292 # -----------------------------------------------------------------------
2294 my $home_org = $patron->home_ou;
2295 my $req_org = $request_lib->id;
2297 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2299 $prox_cache{$home_org} =
2300 $e->search_actor_org_unit_proximity({from_org => $home_org})
2301 unless $prox_cache{$home_org};
2302 my $home_prox = $prox_cache{$home_org};
2305 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2306 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2308 my @keys = sort { $a <=> $b } keys %buckets;
2311 if( $home_org ne $req_org ) {
2312 # -----------------------------------------------------------------------
2313 # shove the copies close to the request_lib into the primary buckets
2314 # directly before the farthest away copies. That way, they are not
2315 # given priority, but they are checked before the farthest copies.
2316 # -----------------------------------------------------------------------
2317 $prox_cache{$req_org} =
2318 $e->search_actor_org_unit_proximity({from_org => $req_org})
2319 unless $prox_cache{$req_org};
2320 my $req_prox = $prox_cache{$req_org};
2323 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2324 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2326 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2327 my $new_key = $highest_key - 0.5; # right before the farthest prox
2328 my @keys2 = sort { $a <=> $b } keys %buckets2;
2329 for my $key (@keys2) {
2330 last if $key >= $highest_key;
2331 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2335 @keys = sort { $a <=> $b } keys %buckets;
2340 OUTER: for my $key (@keys) {
2341 my @cps = @{$buckets{$key}};
2343 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2345 for my $copyid (@cps) {
2347 next if $seen{$copyid};
2348 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2349 my $copy = $e->retrieve_asset_copy($copyid);
2350 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2352 unless($title) { # grab the title if we don't already have it
2353 my $vol = $e->retrieve_asset_call_number(
2354 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2355 $title = $vol->record;
2358 @status = verify_copy_for_hold(
2359 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2361 last OUTER if $status[0];
2366 if (!defined($empty_ok)) {
2367 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2368 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2371 return (1,0) if ($empty_ok);
2377 sub _check_volume_hold_is_possible {
2378 my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2379 my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
2380 my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
2381 $logger->info("checking possibility of volume hold for volume ".$vol->id);
2386 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2387 "payload" => {"fail_part" => "no_ultimate_items"}
2393 for my $copy ( @$copies ) {
2394 @status = verify_copy_for_hold(
2395 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
2403 sub verify_copy_for_hold {
2404 my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib ) = @_;
2405 $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
2406 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2407 { patron => $patron,
2408 requestor => $requestor,
2411 title_descriptor => $title->fixed_fields, # this is fleshed into the title object
2412 pickup_lib => $pickup_lib,
2413 request_lib => $request_lib,
2415 show_event_list => 1
2420 (not scalar @$permitted), # true if permitted is an empty arrayref
2422 ($copy->circ_lib == $pickup_lib) and
2423 ($copy->status == OILS_COPY_STATUS_AVAILABLE)
2431 sub find_nearest_permitted_hold {
2434 my $editor = shift; # CStoreEditor object
2435 my $copy = shift; # copy to target
2436 my $user = shift; # staff
2437 my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
2439 my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
2441 my $bc = $copy->barcode;
2443 # find any existing holds that already target this copy
2444 my $old_holds = $editor->search_action_hold_request(
2445 { current_copy => $copy->id,
2446 cancel_time => undef,
2447 capture_time => undef
2451 # hold->type "R" means we need this copy
2452 for my $h (@$old_holds) { return ($h) if $h->hold_type eq 'R'; }
2455 my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
2457 $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
2458 " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
2460 my $fifo = $U->ou_ancestor_setting_value($user->ws_ou, 'circ.holds_fifo');
2462 # search for what should be the best holds for this copy to fulfill
2463 my $best_holds = $U->storagereq(
2464 "open-ils.storage.action.hold_request.nearest_hold.atomic",
2465 $user->ws_ou, $copy->id, 10, $hold_stall_interval, $fifo );
2467 unless(@$best_holds) {
2469 if( my $hold = $$old_holds[0] ) {
2470 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2474 $logger->info("circulator: no suitable holds found for copy $bc");
2475 return (undef, $evt);
2481 # for each potential hold, we have to run the permit script
2482 # to make sure the hold is actually permitted.
2485 for my $holdid (@$best_holds) {
2486 next unless $holdid;
2487 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
2489 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
2490 my $reqr = $reqr_cache{$hold->requestor} || $editor->retrieve_actor_user($hold->requestor);
2491 my $rlib = $org_cache{$hold->request_lib} || $editor->retrieve_actor_org_unit($hold->request_lib);
2493 $reqr_cache{$hold->requestor} = $reqr;
2494 $org_cache{$hold->request_lib} = $rlib;
2496 # see if this hold is permitted
2497 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2498 { patron_id => $hold->usr,
2501 pickup_lib => $hold->pickup_lib,
2502 request_lib => $rlib,
2514 unless( $best_hold ) { # no "good" permitted holds were found
2515 if( my $hold = $$old_holds[0] ) { # can we return a pre-targeted hold?
2516 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2521 $logger->info("circulator: no suitable holds found for copy $bc");
2522 return (undef, $evt);
2525 $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
2527 # indicate a permitted hold was found
2528 return $best_hold if $check_only;
2530 # we've found a permitted hold. we need to "grab" the copy
2531 # to prevent re-targeted holds (next part) from re-grabbing the copy
2532 $best_hold->current_copy($copy->id);
2533 $editor->update_action_hold_request($best_hold)
2534 or return (undef, $editor->event);
2539 # re-target any other holds that already target this copy
2540 for my $old_hold (@$old_holds) {
2541 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
2542 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
2543 $old_hold->id." after a better hold [".$best_hold->id."] was found");
2544 $old_hold->clear_current_copy;
2545 $old_hold->clear_prev_check_time;
2546 $editor->update_action_hold_request($old_hold)
2547 or return (undef, $editor->event);
2548 push(@retarget, $old_hold->id);
2551 return ($best_hold, undef, (@retarget) ? \@retarget : undef);
2559 __PACKAGE__->register_method(
2560 method => 'all_rec_holds',
2561 api_name => 'open-ils.circ.holds.retrieve_all_from_title',
2565 my( $self, $conn, $auth, $title_id, $args ) = @_;
2567 my $e = new_editor(authtoken=>$auth);
2568 $e->checkauth or return $e->event;
2569 $e->allowed('VIEW_HOLD') or return $e->event;
2572 $args->{fulfillment_time} = undef; # we don't want to see old fulfilled holds
2573 $args->{cancel_time} = undef;
2575 my $resp = { volume_holds => [], copy_holds => [], metarecord_holds => [] };
2577 my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
2579 $resp->{metarecord_holds} = $e->search_action_hold_request(
2580 { hold_type => OILS_HOLD_TYPE_METARECORD,
2581 target => $mr_map->metarecord,
2587 $resp->{title_holds} = $e->search_action_hold_request(
2589 hold_type => OILS_HOLD_TYPE_TITLE,
2590 target => $title_id,
2594 my $vols = $e->search_asset_call_number(
2595 { record => $title_id, deleted => 'f' }, {idlist=>1});
2597 return $resp unless @$vols;
2599 $resp->{volume_holds} = $e->search_action_hold_request(
2601 hold_type => OILS_HOLD_TYPE_VOLUME,
2606 my $copies = $e->search_asset_copy(
2607 { call_number => $vols, deleted => 'f' }, {idlist=>1});
2609 return $resp unless @$copies;
2611 $resp->{copy_holds} = $e->search_action_hold_request(
2613 hold_type => OILS_HOLD_TYPE_COPY,
2625 __PACKAGE__->register_method(
2626 method => 'uber_hold',
2628 api_name => 'open-ils.circ.hold.details.retrieve'
2632 my($self, $client, $auth, $hold_id, $args) = @_;
2633 my $e = new_editor(authtoken=>$auth);
2634 $e->checkauth or return $e->event;
2635 return uber_hold_impl($e, $hold_id, $args);
2638 __PACKAGE__->register_method(
2639 method => 'batch_uber_hold',
2642 api_name => 'open-ils.circ.hold.details.batch.retrieve'
2645 sub batch_uber_hold {
2646 my($self, $client, $auth, $hold_ids, $args) = @_;
2647 my $e = new_editor(authtoken=>$auth);
2648 $e->checkauth or return $e->event;
2649 $client->respond(uber_hold_impl($e, $_, $args)) for @$hold_ids;
2653 sub uber_hold_impl {
2654 my($e, $hold_id, $args) = @_;
2659 my $hold = $e->retrieve_action_hold_request(
2664 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
2667 ) or return $e->event;
2669 if($hold->usr->id ne $e->requestor->id) {
2670 # A user is allowed to see his/her own holds
2671 $e->allowed('VIEW_HOLD') or return $e->event;
2672 $hold->notes( # filter out any non-staff ("private") notes
2673 [ grep { !$U->is_true($_->staff) } @{$hold->notes} ] );
2676 # caller is asking for own hold, but may not have permission to view staff notes
2677 unless($e->allowed('VIEW_HOLD')) {
2678 $hold->notes( # filter out any staff notes
2679 [ grep { $U->is_true($_->staff) } @{$hold->notes} ] );
2683 my $user = $hold->usr;
2684 $hold->usr($user->id);
2687 my( $mvr, $volume, $copy, $issuance, $bre ) = find_hold_mvr($e, $hold, $args->{suppress_mvr});
2689 flesh_hold_notices([$hold], $e) unless $args->{suppress_notices};
2690 flesh_hold_transits([$hold]) unless $args->{suppress_transits};
2692 my $details = retrieve_hold_queue_status_impl($e, $hold);
2701 $resp->{mvr} = $mvr unless $args->{suppress_mvr};
2702 unless($args->{suppress_patron_details}) {
2703 my $card = $e->retrieve_actor_card($user->card) or return $e->event;
2704 $resp->{patron_first} = $user->first_given_name,
2705 $resp->{patron_last} = $user->family_name,
2706 $resp->{patron_barcode} = $card->barcode,
2707 $resp->{patron_alias} = $user->alias,
2710 $resp->{bre} = $bre if $args->{include_bre};
2717 # -----------------------------------------------------
2718 # Returns the MVR object that represents what the
2720 # -----------------------------------------------------
2722 my( $e, $hold, $no_mvr ) = @_;
2729 if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2730 my $mr = $e->retrieve_metabib_metarecord($hold->target)
2731 or return $e->event;
2732 $tid = $mr->master_record;
2734 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
2735 $tid = $hold->target;
2737 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2738 $volume = $e->retrieve_asset_call_number($hold->target)
2739 or return $e->event;
2740 $tid = $volume->record;
2742 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2743 $issuance = $e->retrieve_serial_issuance([
2745 {flesh => 1, flesh_fields => {siss => [ qw/subscription/ ]}}
2746 ]) or return $e->event;
2748 $tid = $issuance->subscription->record_entry;
2750 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_COPY ) {
2751 $copy = $e->retrieve_asset_copy([
2753 {flesh => 1, flesh_fields => {acp => ['call_number']}}
2754 ]) or return $e->event;
2756 $volume = $copy->call_number;
2757 $tid = $volume->record;
2760 if(!$copy and ref $hold->current_copy ) {
2761 $copy = $hold->current_copy;
2762 $hold->current_copy($copy->id);
2765 if(!$volume and $copy) {
2766 $volume = $e->retrieve_asset_call_number($copy->call_number);
2769 # TODO return metarcord mvr for M holds
2770 my $title = $e->retrieve_biblio_record_entry($tid);
2771 return ( ($no_mvr) ? undef : $U->record_to_mvr($title), $volume, $copy, $issuance, $title );
2774 __PACKAGE__->register_method(
2775 method => 'clear_shelf_cache',
2776 api_name => 'open-ils.circ.hold.clear_shelf.get_cache',
2780 Returns the holds processed with the given cache key
2785 sub clear_shelf_cache {
2786 my($self, $client, $auth, $cache_key, $chunk_size) = @_;
2787 my $e = new_editor(authtoken => $auth, xact => 1);
2788 return $e->die_event unless $e->checkauth and $e->allowed('VIEW_HOLD');
2791 my $hold_data = OpenSRF::Utils::Cache->new('global')->get_cache($cache_key);
2794 $logger->info("no hold data found in cache"); # XXX TODO return event
2800 foreach (keys %$hold_data) {
2801 $maximum += scalar(@{ $hold_data->{$_} });
2803 $client->respond({"maximum" => $maximum, "progress" => 0});
2805 for my $action (sort keys %$hold_data) {
2806 while (@{$hold_data->{$action}}) {
2807 my @hid_chunk = splice @{$hold_data->{$action}}, 0, $chunk_size;
2809 my $result_chunk = $e->json_query({
2811 "acp" => ["barcode"],
2813 first_given_name second_given_name family_name alias
2823 "field" => "id", "fkey" => "current_copy",
2826 "field" => "id", "fkey" => "call_number",
2829 "field" => "id", "fkey" => "record"
2833 "acpl" => {"field" => "id", "fkey" => "location"}
2836 "au" => {"field" => "id", "fkey" => "usr"}
2839 "where" => {"+ahr" => {"id" => \@hid_chunk}}
2840 }, {"substream" => 1}) or return $e->die_event;
2844 +{"action" => $action, "hold_details" => $_}
2855 __PACKAGE__->register_method(
2856 method => 'clear_shelf_process',
2858 api_name => 'open-ils.circ.hold.clear_shelf.process',
2861 1. Find all holds that have expired on the holds shelf
2863 3. If a clear-shelf status is configured, put targeted copies into this status
2864 4. Divide copies into 3 groups: items to transit, items to reshelve, and items
2865 that are needed for holds. No subsequent action is taken on the holds
2866 or items after grouping.
2871 sub clear_shelf_process {
2872 my($self, $client, $auth, $org_id) = @_;
2874 my $e = new_editor(authtoken=>$auth, xact => 1);
2875 $e->checkauth or return $e->die_event;
2876 my $cache = OpenSRF::Utils::Cache->new('global');
2878 $org_id ||= $e->requestor->ws_ou;
2879 $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
2881 my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
2883 # Find holds on the shelf that have been there too long
2884 my $hold_ids = $e->search_action_hold_request(
2885 { shelf_expire_time => {'<' => 'now'},
2886 pickup_lib => $org_id,
2887 cancel_time => undef,
2888 fulfillment_time => undef,
2889 shelf_time => {'!=' => undef},
2890 capture_time => {'!=' => undef},
2891 current_copy => {'!=' => undef},
2897 my $chunk_size = 25; # chunked status updates
2899 for my $hold_id (@$hold_ids) {
2901 $logger->info("Clear shelf processing hold $hold_id");
2903 my $hold = $e->retrieve_action_hold_request([
2906 flesh_fields => {ahr => ['current_copy']}
2910 $hold->cancel_time('now');
2911 $hold->cancel_cause(2); # Hold Shelf expiration
2912 $e->update_action_hold_request($hold) or return $e->die_event;
2914 my $copy = $hold->current_copy;
2916 if($copy_status or $copy_status == 0) {
2917 # if a clear-shelf copy status is defined, update the copy
2918 $copy->status($copy_status);
2919 $copy->edit_date('now');
2920 $copy->editor($e->requestor->id);
2921 $e->update_asset_copy($copy) or return $e->die_event;
2924 push(@holds, $hold);
2925 $client->respond({maximum => scalar(@holds), progress => $counter}) if ( (++$counter % $chunk_size) == 0);
2936 for my $hold (@holds) {
2938 my $copy = $hold->current_copy;
2939 my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
2943 push(@{$cache_data{hold}}, $hold->id); # copy is needed for a hold
2945 } elsif($copy->circ_lib != $e->requestor->ws_ou) {
2947 push(@{$cache_data{transit}}, $hold->id); # copy needs to transit
2951 push(@{$cache_data{shelf}}, $hold->id); # copy needs to go back to the shelf
2955 my $cache_key = md5_hex(time . $$ . rand());
2956 $logger->info("clear_shelf_cache: storing under $cache_key");
2957 $cache->put_cache($cache_key, \%cache_data, 7200); # TODO: 2 hours. configurable?
2959 # tell the client we're done
2960 $client->respond_complete({cache_key => $cache_key});
2962 # fire off the hold cancelation trigger and wait for response so don't flood the service
2963 $U->create_events_for_hook(
2964 'hold_request.cancel.expire_holds_shelf',
2965 $_, $org_id, undef, undef, 1) for @holds;
2968 # tell the client we're done
2969 $client->respond_complete;
2973 __PACKAGE__->register_method(
2974 method => 'usr_hold_summary',
2975 api_name => 'open-ils.circ.holds.user_summary',
2977 Returns a summary of holds statuses for a given user
2981 sub usr_hold_summary {
2982 my($self, $conn, $auth, $user_id) = @_;
2984 my $e = new_editor(authtoken=>$auth);
2985 $e->checkauth or return $e->event;
2986 $e->allowed('VIEW_HOLD') or return $e->event;
2988 my $holds = $e->search_action_hold_request(
2991 fulfillment_time => undef,
2992 cancel_time => undef,
2996 my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
2997 $summary{_hold_status($e, $_)} += 1 for @$holds;
3003 __PACKAGE__->register_method(
3004 method => 'hold_has_copy_at',
3005 api_name => 'open-ils.circ.hold.has_copy_at',
3008 'Returns the ID of the found copy and name of the shelving location if there is ' .
3009 'an available copy at the specified org unit. Returns empty hash otherwise. ' .
3010 'The anticipated use for this method is to determine whether an item is ' .
3011 'available at the library where the user is placing the hold (or, alternatively, '.
3012 'at the pickup library) to encourage bypassing the hold placement and just ' .
3013 'checking out the item.' ,
3015 { desc => 'Authentication Token', type => 'string' },
3016 { desc => 'Method Arguments. Options include: hold_type, hold_target, org_unit. '
3017 . 'hold_type is the hold type code (T, V, C, M, ...). '
3018 . 'hold_target is the identifier of the hold target object. '
3019 . 'org_unit is org unit ID.',
3024 desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
3030 sub hold_has_copy_at {
3031 my($self, $conn, $auth, $args) = @_;
3033 my $e = new_editor(authtoken=>$auth);
3034 $e->checkauth or return $e->event;
3036 my $hold_type = $$args{hold_type};
3037 my $hold_target = $$args{hold_target};
3038 my $org_unit = $$args{org_unit};
3041 select => {acp => ['id'], acpl => ['name']},
3044 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
3045 ccs => {field => 'id', filter => { holdable => 't'}, fkey => 'status' }
3048 where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit}},
3052 if($hold_type eq 'C') {
3054 $query->{where}->{'+acp'}->{id} = $hold_target;
3056 } elsif($hold_type eq 'V') {
3058 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3060 } elsif($hold_type eq 'T') {
3062 $query->{from}->{acp}->{acn} = {
3064 fkey => 'call_number',
3068 filter => {id => $hold_target},
3076 $query->{from}->{acp}->{acn} = {
3078 fkey => 'call_number',
3087 filter => {metarecord => $hold_target},
3095 my $res = $e->json_query($query)->[0] or return {};
3096 return {copy => $res->{id}, location => $res->{name}} if $res;
3100 # returns true if the user already has an item checked out
3101 # that could be used to fulfill the requested hold.
3102 sub hold_item_is_checked_out {
3103 my($e, $user_id, $hold_type, $hold_target) = @_;
3106 select => {acp => ['id']},
3107 from => {acp => {}},
3111 in => { # copies for circs the user has checked out
3112 select => {circ => ['target_copy']},
3116 checkin_time => undef,
3118 {stop_fines => ["MAXFINES","LONGOVERDUE"]},
3119 {stop_fines => undef}
3129 if($hold_type eq 'C' || $hold_type eq 'R' || $hold_type eq 'F') {
3131 $query->{where}->{'+acp'}->{id}->{in}->{where}->{'target_copy'} = $hold_target;
3133 } elsif($hold_type eq 'V') {
3135 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3137 } elsif($hold_type eq 'I') {
3139 $query->{from}->{acp}->{sitem} = {
3142 filter => {issuance => $hold_target},
3145 } elsif($hold_type eq 'T') {
3147 $query->{from}->{acp}->{acn} = {
3149 fkey => 'call_number',
3153 filter => {id => $hold_target},
3161 $query->{from}->{acp}->{acn} = {
3163 fkey => 'call_number',
3172 filter => {metarecord => $hold_target},
3180 return $e->json_query($query)->[0];
3183 __PACKAGE__->register_method(
3184 method => 'change_hold_title',
3185 api_name => 'open-ils.circ.hold.change_title',
3188 Updates all title level holds targeting the specified bibs to point a new bib./,
3190 { desc => 'Authentication Token', type => 'string' },
3191 { desc => 'New Target Bib Id', type => 'number' },
3192 { desc => 'Old Target Bib Ids', type => 'array' },
3194 return => { desc => '1 on success' }
3198 sub change_hold_title {
3199 my( $self, $client, $auth, $new_bib_id, $bib_ids ) = @_;
3201 my $e = new_editor(authtoken=>$auth, xact=>1);
3202 return $e->die_event unless $e->checkauth;
3204 my $holds = $e->search_action_hold_request(
3207 cancel_time => undef,
3208 fulfillment_time => undef,
3214 flesh_fields => { ahr => ['usr'] }
3220 for my $hold (@$holds) {
3221 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3222 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3223 $hold->target( $new_bib_id );
3224 $e->update_action_hold_request($hold) or return $e->die_event;
3233 __PACKAGE__->register_method(
3234 method => 'rec_hold_count',
3235 api_name => 'open-ils.circ.bre.holds.count',
3237 desc => q/Returns the total number of holds that target the
3238 selected bib record or its associated copies and call_numbers/,
3240 { desc => 'Bib ID', type => 'number' },
3242 return => {desc => 'Hold count', type => 'number'}
3246 __PACKAGE__->register_method(
3247 method => 'rec_hold_count',
3248 api_name => 'open-ils.circ.mmr.holds.count',
3250 desc => q/Returns the total number of holds that target the
3251 selected metarecord or its associated copies, call_numbers, and bib records/,
3253 { desc => 'Metarecord ID', type => 'number' },
3255 return => {desc => 'Hold count', type => 'number'}
3259 sub rec_hold_count {
3260 my($self, $conn, $target_id) = @_;
3267 filter => {metarecord => $target_id}
3274 filter => { id => $target_id },
3279 if($self->api_name =~ /mmr/) {
3280 delete $bre_join->{bre}->{filter};
3281 $bre_join->{bre}->{join} = $mmr_join;
3287 fkey => 'call_number',
3293 select => {ahr => [{column => 'id', transform => 'count', alias => 'count'}]},
3297 cancel_time => undef,
3298 fulfillment_time => undef,
3305 select => {acp => ['id']},
3306 from => { acp => $cn_join }
3316 select => {acn => ['id']},
3317 from => {acn => $bre_join}
3325 target => $target_id
3333 if($self->api_name =~ /mmr/) {
3334 $query->{where}->{'+ahr'}->{'-or'}->[2] = {
3339 select => {bre => ['id']},
3340 from => {bre => $mmr_join}
3346 $query->{where}->{'+ahr'}->{'-or'}->[3] = {
3349 target => $target_id
3355 return new_editor()->json_query($query)->[0]->{count};