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', type => 'object' }
100 desc => 'Undef on success, -1 on missing arg, event (or ref to array of events) on error(s)',
105 __PACKAGE__->register_method(
106 method => "create_hold",
107 api_name => "open-ils.circ.holds.create.override",
108 notes => '@see open-ils.circ.holds.create',
110 desc => "If the recipient is not allowed to receive the requested hold, " .
111 "call this method to attempt the override",
113 { desc => 'Authentication token', type => 'string' },
114 { desc => 'Hold object for hold to be created', type => 'object' }
117 desc => 'Undef on success, -1 on missing arg, event (or ref to array of events) on error(s)',
123 my( $self, $conn, $auth, $hold ) = @_;
124 return -1 unless $hold;
125 my $e = new_editor(authtoken=>$auth, xact=>1);
126 return $e->die_event unless $e->checkauth;
128 my $override = 1 if $self->api_name =~ /override/;
132 my $requestor = $e->requestor;
133 my $recipient = $requestor;
135 if( $requestor->id ne $hold->usr ) {
136 # Make sure the requestor is allowed to place holds for
137 # the recipient if they are not the same people
138 $recipient = $e->retrieve_actor_user($hold->usr) or return $e->die_event;
139 $e->allowed('REQUEST_HOLDS', $recipient->home_ou) or return $e->die_event;
142 # If the related org setting tells us to, block if patron privs have expired
143 my $expire_setting = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_BLOCK_HOLD_FOR_EXPIRED_PATRON);
144 if ($expire_setting) {
145 my $expire = DateTime::Format::ISO8601->new->parse_datetime(
146 cleanse_ISO8601($recipient->expire_date));
148 push( @events, OpenILS::Event->new(
149 'PATRON_ACCOUNT_EXPIRED',
150 "payload" => {"fail_part" => "actor.usr.privs_expired"}
151 )) if( CORE::time > $expire->epoch ) ;
154 # Now make sure the recipient is allowed to receive the specified hold
155 my $porg = $recipient->home_ou;
156 my $rid = $e->requestor->id;
157 my $t = $hold->hold_type;
159 # See if a duplicate hold already exists
161 usr => $recipient->id,
163 fulfillment_time => undef,
164 target => $hold->target,
165 cancel_time => undef,
168 $sargs->{holdable_formats} = $hold->holdable_formats if $t eq 'M';
170 my $existing = $e->search_action_hold_request($sargs);
171 push( @events, OpenILS::Event->new('HOLD_EXISTS')) if @$existing;
173 my $checked_out = hold_item_is_checked_out($e, $recipient->id, $hold->hold_type, $hold->target);
174 push( @events, OpenILS::Event->new('HOLD_ITEM_CHECKED_OUT')) if $checked_out;
176 if ( $t eq OILS_HOLD_TYPE_METARECORD ) {
177 return $e->die_event unless $e->allowed('MR_HOLDS', $porg);
178 } elsif ( $t eq OILS_HOLD_TYPE_TITLE ) {
179 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
180 } elsif ( $t eq OILS_HOLD_TYPE_VOLUME ) {
181 return $e->die_event unless $e->allowed('VOLUME_HOLDS', $porg);
182 } elsif ( $t eq OILS_HOLD_TYPE_ISSUANCE ) {
183 return $e->die_event unless $e->allowed('ISSUANCE_HOLDS', $porg);
184 } elsif ( $t eq OILS_HOLD_TYPE_COPY ) {
185 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
186 } elsif ( $t eq OILS_HOLD_TYPE_FORCE ) {
187 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
188 } elsif ( $t eq OILS_HOLD_TYPE_RECALL ) {
189 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
197 for my $evt (@events) {
199 my $name = $evt->{textcode};
200 return $e->die_event unless $e->allowed("$name.override", $porg);
204 # set the configured expire time
205 unless($hold->expire_time) {
206 my $interval = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_HOLD_EXPIRE);
208 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
209 $hold->expire_time($U->epoch2ISO8601($date->epoch));
213 $hold->requestor($e->requestor->id);
214 $hold->request_lib($e->requestor->ws_ou);
215 $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
216 $hold = $e->create_action_hold_request($hold) or return $e->die_event;
220 $conn->respond_complete($hold->id);
223 'open-ils.storage.action.hold_request.copy_targeter',
224 undef, $hold->id ) unless $U->is_true($hold->frozen);
229 # makes sure that a user has permission to place the type of requested hold
230 # returns the Perm exception if not allowed, returns undef if all is well
231 sub _check_holds_perm {
232 my($type, $user_id, $org_id) = @_;
236 $evt = $apputils->check_perms($user_id, $org_id, "MR_HOLDS" );
237 } elsif ($type eq "T") {
238 $evt = $apputils->check_perms($user_id, $org_id, "TITLE_HOLDS" );
239 } elsif($type eq "V") {
240 $evt = $apputils->check_perms($user_id, $org_id, "VOLUME_HOLDS");
241 } elsif($type eq "C") {
242 $evt = $apputils->check_perms($user_id, $org_id, "COPY_HOLDS" );
249 # tests if the given user is allowed to place holds on another's behalf
250 sub _check_request_holds_perm {
253 if (my $evt = $apputils->check_perms(
254 $user_id, $org_id, "REQUEST_HOLDS")) {
259 my $ses_is_req_note = 'The login session is the requestor. If the requestor is different from the user, ' .
260 'then the requestor must have VIEW_HOLD permissions';
262 __PACKAGE__->register_method(
263 method => "retrieve_holds_by_id",
264 api_name => "open-ils.circ.holds.retrieve_by_id",
266 desc => "Retrieve the hold, with hold transits attached, for the specified ID. $ses_is_req_note",
268 { desc => 'Authentication token', type => 'string' },
269 { desc => 'Hold ID', type => 'number' }
272 desc => 'Hold object with transits attached, event on error',
278 sub retrieve_holds_by_id {
279 my($self, $client, $auth, $hold_id) = @_;
280 my $e = new_editor(authtoken=>$auth);
281 $e->checkauth or return $e->event;
282 $e->allowed('VIEW_HOLD') or return $e->event;
284 my $holds = $e->search_action_hold_request(
286 { id => $hold_id , fulfillment_time => undef },
288 order_by => { ahr => "request_time" },
290 flesh_fields => {ahr => ['notes']}
295 flesh_hold_transits($holds);
296 flesh_hold_notices($holds, $e);
301 __PACKAGE__->register_method(
302 method => "retrieve_holds",
303 api_name => "open-ils.circ.holds.retrieve",
305 desc => "Retrieves all the holds, with hold transits attached, for the specified user. $ses_is_req_note",
307 { desc => 'Authentication token', type => 'string' },
308 { desc => 'User ID', type => 'integer' }
311 desc => 'list of holds, event on error',
316 __PACKAGE__->register_method(
317 method => "retrieve_holds",
318 api_name => "open-ils.circ.holds.id_list.retrieve",
321 desc => "Retrieves all the hold IDs, for the specified user. $ses_is_req_note",
323 { desc => 'Authentication token', type => 'string' },
324 { desc => 'User ID', type => 'integer' }
327 desc => 'list of holds, event on error',
332 __PACKAGE__->register_method(
333 method => "retrieve_holds",
334 api_name => "open-ils.circ.holds.canceled.retrieve",
337 desc => "Retrieves all the cancelled holds for the specified user. $ses_is_req_note",
339 { desc => 'Authentication token', type => 'string' },
340 { desc => 'User ID', type => 'integer' }
343 desc => 'list of holds, event on error',
348 __PACKAGE__->register_method(
349 method => "retrieve_holds",
350 api_name => "open-ils.circ.holds.canceled.id_list.retrieve",
353 desc => "Retrieves list of cancelled hold IDs for the specified user. $ses_is_req_note",
355 { desc => 'Authentication token', type => 'string' },
356 { desc => 'User ID', type => 'integer' }
359 desc => 'list of hold IDs, event on error',
366 my ($self, $client, $auth, $user_id) = @_;
368 my $e = new_editor(authtoken=>$auth);
369 return $e->event unless $e->checkauth;
370 $user_id = $e->requestor->id unless defined $user_id;
372 my $notes_filter = {staff => 'f'};
373 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
374 unless($user_id == $e->requestor->id) {
375 if($e->allowed('VIEW_HOLD', $user->home_ou)) {
376 $notes_filter = {staff => 't'}
378 my $allowed = OpenILS::Application::Actor::Friends->friend_perm_allowed(
379 $e, $user_id, $e->requestor->id, 'hold.view');
380 return $e->event unless $allowed;
383 # staff member looking at his/her own holds can see staff and non-staff notes
384 $notes_filter = {} if $e->allowed('VIEW_HOLD', $user->home_ou);
389 if($self->api_name !~ /canceled/) {
391 # Fetch the active holds
393 $holds = $e->search_action_hold_request([
395 fulfillment_time => undef,
396 cancel_time => undef,
398 {order_by => {ahr => "request_time"}}
403 # Fetch the canceled holds
406 my $cancel_count = $U->ou_ancestor_setting_value(
407 $e->requestor->ws_ou, 'circ.holds.canceled.display_count', $e);
409 unless($cancel_count) {
410 $cancel_age = $U->ou_ancestor_setting_value(
411 $e->requestor->ws_ou, 'circ.holds.canceled.display_age', $e);
414 if($cancel_count) { # limit by count
416 # find at most cancel_count canceled holds
417 $holds = $e->search_action_hold_request([
419 fulfillment_time => undef,
420 cancel_time => {'!=' => undef},
422 {order_by => {ahr => "cancel_time desc"}, limit => $cancel_count}
425 } elsif($cancel_age) { # limit by age
427 # find all of the canceled holds that were canceled within the configured time frame
428 my $date = DateTime->now->subtract(seconds => OpenSRF::Utils::interval_to_seconds($cancel_age));
429 $date = $U->epoch2ISO8601($date->epoch);
431 $holds = $e->search_action_hold_request([
433 fulfillment_time => undef,
434 cancel_time => {'>=' => $date},
436 {order_by => {ahr => "cancel_time desc"}}
441 if( $self->api_name !~ /id_list/ ) {
442 for my $hold ( @$holds ) {
443 $hold->notes($e->search_action_hold_request_note({hold => $hold->id, %$notes_filter}));
445 $e->search_action_hold_transit_copy([
447 {order_by => {ahtc => 'id desc'}, limit => 1}])->[0]
453 return [ map { $_->id } @$holds ];
457 __PACKAGE__->register_method(
458 method => 'user_hold_count',
459 api_name => 'open-ils.circ.hold.user.count'
462 sub user_hold_count {
463 my ( $self, $conn, $auth, $userid ) = @_;
464 my $e = new_editor( authtoken => $auth );
465 return $e->event unless $e->checkauth;
466 my $patron = $e->retrieve_actor_user($userid)
468 return $e->event unless $e->allowed( 'VIEW_HOLD', $patron->home_ou );
469 return __user_hold_count( $self, $e, $userid );
472 sub __user_hold_count {
473 my ( $self, $e, $userid ) = @_;
474 my $holds = $e->search_action_hold_request(
477 fulfillment_time => undef,
478 cancel_time => undef,
483 return scalar(@$holds);
487 __PACKAGE__->register_method(
488 method => "retrieve_holds_by_pickup_lib",
489 api_name => "open-ils.circ.holds.retrieve_by_pickup_lib",
491 "Retrieves all the holds, with hold transits attached, for the specified pickup_ou id."
494 __PACKAGE__->register_method(
495 method => "retrieve_holds_by_pickup_lib",
496 api_name => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
497 notes => "Retrieves all the hold ids for the specified pickup_ou id. "
500 sub retrieve_holds_by_pickup_lib {
501 my ($self, $client, $login_session, $ou_id) = @_;
503 #FIXME -- put an appropriate permission check here
504 #my( $user, $target, $evt ) = $apputils->checkses_requestor(
505 # $login_session, $user_id, 'VIEW_HOLD' );
506 #return $evt if $evt;
508 my $holds = $apputils->simplereq(
510 "open-ils.cstore.direct.action.hold_request.search.atomic",
512 pickup_lib => $ou_id ,
513 fulfillment_time => undef,
516 { order_by => { ahr => "request_time" } }
519 if ( ! $self->api_name =~ /id_list/ ) {
520 flesh_hold_transits($holds);
524 return [ map { $_->id } @$holds ];
528 __PACKAGE__->register_method(
529 method => "uncancel_hold",
530 api_name => "open-ils.circ.hold.uncancel"
534 my($self, $client, $auth, $hold_id) = @_;
535 my $e = new_editor(authtoken=>$auth, xact=>1);
536 return $e->die_event unless $e->checkauth;
538 my $hold = $e->retrieve_action_hold_request($hold_id)
539 or return $e->die_event;
540 return $e->die_event unless $e->allowed('CANCEL_HOLDS', $hold->request_lib);
542 if ($hold->fulfillment_time) {
546 unless ($hold->cancel_time) {
551 # if configured to reset the request time, also reset the expire time
552 if($U->ou_ancestor_setting_value(
553 $hold->request_lib, 'circ.holds.uncancel.reset_request_time', $e)) {
555 $hold->request_time('now');
556 my $interval = $U->ou_ancestor_setting_value($hold->request_lib, OILS_SETTING_HOLD_EXPIRE);
558 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
559 $hold->expire_time($U->epoch2ISO8601($date->epoch));
563 $hold->clear_cancel_time;
564 $hold->clear_cancel_cause;
565 $hold->clear_cancel_note;
566 $e->update_action_hold_request($hold) or return $e->die_event;
569 $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
575 __PACKAGE__->register_method(
576 method => "cancel_hold",
577 api_name => "open-ils.circ.hold.cancel",
579 desc => 'Cancels the specified hold. The login session is the requestor. If the requestor is different from the usr field ' .
580 'on the hold, the requestor must have CANCEL_HOLDS permissions. The hold may be either the hold object or the hold id',
582 {desc => 'Authentication token', type => 'string'},
583 {desc => 'Hold ID', type => 'number'},
584 {desc => 'Cause of Cancellation', type => 'string'},
585 {desc => 'Note', type => 'string'}
588 desc => '1 on success, event on error'
594 my($self, $client, $auth, $holdid, $cause, $note) = @_;
596 my $e = new_editor(authtoken=>$auth, xact=>1);
597 return $e->die_event unless $e->checkauth;
599 my $hold = $e->retrieve_action_hold_request($holdid)
600 or return $e->die_event;
602 if( $e->requestor->id ne $hold->usr ) {
603 return $e->die_event unless $e->allowed('CANCEL_HOLDS');
606 if ($hold->cancel_time) {
611 # If the hold is captured, reset the copy status
612 if( $hold->capture_time and $hold->current_copy ) {
614 my $copy = $e->retrieve_asset_copy($hold->current_copy)
615 or return $e->die_event;
617 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
618 $logger->info("canceling hold $holdid whose item is on the holds shelf");
619 # $logger->info("setting copy to status 'reshelving' on hold cancel");
620 # $copy->status(OILS_COPY_STATUS_RESHELVING);
621 # $copy->editor($e->requestor->id);
622 # $copy->edit_date('now');
623 # $e->update_asset_copy($copy) or return $e->event;
625 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
628 $logger->warn("! canceling hold [$hid] that is in transit");
629 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
632 my $trans = $e->retrieve_action_transit_copy($transid);
633 # Leave the transit alive, but set the copy status to
634 # reshelving so it will be properly reshelved when it gets back home
636 $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
637 $e->update_action_transit_copy($trans) or return $e->die_event;
643 $hold->cancel_time('now');
644 $hold->cancel_cause($cause);
645 $hold->cancel_note($note);
646 $e->update_action_hold_request($hold)
647 or return $e->die_event;
649 delete_hold_copy_maps($self, $e, $hold->id);
653 $U->create_events_for_hook('hold_request.cancel.staff', $hold, $hold->pickup_lib)
654 if $e->requestor->id != $hold->usr;
659 sub delete_hold_copy_maps {
664 my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
666 $editor->delete_action_hold_copy_map($_)
667 or return $editor->event;
673 my $update_hold_desc = 'The login session is the requestor. ' .
674 'If the requestor is different from the usr field on the hold, ' .
675 'the requestor must have UPDATE_HOLDS permissions. ' .
676 'If supplying a hash of hold data, "id" must be included. ' .
677 'The hash is ignored if a hold object is supplied, ' .
678 'so you should supply only one kind of hold data argument.' ;
680 __PACKAGE__->register_method(
681 method => "update_hold",
682 api_name => "open-ils.circ.hold.update",
684 desc => "Updates the specified hold. $update_hold_desc",
686 {desc => 'Authentication token', type => 'string'},
687 {desc => 'Hold Object', type => 'object'},
688 {desc => 'Hash of values to be applied', type => 'object'}
691 desc => 'Hold ID on success, event on error',
697 __PACKAGE__->register_method(
698 method => "batch_update_hold",
699 api_name => "open-ils.circ.hold.update.batch",
702 desc => "Updates the specified hold(s). $update_hold_desc",
704 {desc => 'Authentication token', type => 'string'},
705 {desc => 'Array of hold obejcts', type => 'array' },
706 {desc => 'Array of hashes of values to be applied', type => 'array' }
709 desc => 'Hold ID per success, event per error',
715 my($self, $client, $auth, $hold, $values) = @_;
716 my $e = new_editor(authtoken=>$auth, xact=>1);
717 return $e->die_event unless $e->checkauth;
718 my $resp = update_hold_impl($self, $e, $hold, $values);
719 if ($U->event_code($resp)) {
723 $e->commit; # FIXME: update_hold_impl already does $e->commit ??
727 sub batch_update_hold {
728 my($self, $client, $auth, $hold_list, $values_list) = @_;
729 my $e = new_editor(authtoken=>$auth);
730 return $e->die_event unless $e->checkauth;
732 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.
734 $values_list ||= []; # FIXME: either move this above $count declaration, or send an event if both lists undef. Probably the latter.
736 # FIXME: Failing over to [] guarantees warnings for "Use of unitialized value" in update_hold_impl call.
737 # FIXME: We should be sure we only call update_hold_impl with hold object OR hash, not both.
739 for my $idx (0..$count-1) {
741 my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
742 $e->xact_commit unless $U->event_code($resp);
743 $client->respond($resp);
747 return undef; # not in the register return type, assuming we should always have at least one list populated
750 sub update_hold_impl {
751 my($self, $e, $hold, $values) = @_;
754 $hold = $e->retrieve_action_hold_request($values->{id})
755 or return $e->die_event;
756 for my $k (keys %$values) {
757 if (defined $values->{$k}) {
758 $hold->$k($values->{$k});
760 my $f = "clear_$k"; $hold->$f();
765 my $orig_hold = $e->retrieve_action_hold_request($hold->id)
766 or return $e->die_event;
768 # don't allow the user to be changed
769 return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
771 if($hold->usr ne $e->requestor->id) {
772 # if the hold is for a different user, make sure the
773 # requestor has the appropriate permissions
774 my $usr = $e->retrieve_actor_user($hold->usr)
775 or return $e->die_event;
776 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
780 # --------------------------------------------------------------
781 # Changing the request time is like playing God
782 # --------------------------------------------------------------
783 if($hold->request_time ne $orig_hold->request_time) {
784 return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
785 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
788 # --------------------------------------------------------------
789 # if the hold is on the holds shelf or in transit and the pickup
790 # lib changes we need to create a new transit.
791 # --------------------------------------------------------------
792 if($orig_hold->pickup_lib ne $hold->pickup_lib) {
794 my $status = _hold_status($e, $hold);
796 if($status == 3) { # in transit
798 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
799 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
801 $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
803 # update the transit to reflect the new pickup location
804 my $transit = $e->search_action_hold_transit_copy(
805 {hold=>$hold->id, dest_recv_time => undef})->[0]
806 or return $e->die_event;
808 $transit->prev_dest($transit->dest); # mark the previous destination on the transit
809 $transit->dest($hold->pickup_lib);
810 $e->update_action_hold_transit_copy($transit) or return $e->die_event;
812 } elsif($status == 4) { # on holds shelf
814 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
815 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
817 $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
819 # create the new transit
820 my $evt = transit_hold($e, $orig_hold, $hold, $e->retrieve_asset_copy($hold->current_copy));
825 update_hold_if_frozen($self, $e, $hold, $orig_hold);
826 $e->update_action_hold_request($hold) or return $e->die_event;
829 # a change to mint-condition changes the set of potential copies, so retarget the hold;
830 if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
831 _reset_hold($self, $e->requestor, $hold)
838 my($e, $orig_hold, $hold, $copy) = @_;
839 my $src = $orig_hold->pickup_lib;
840 my $dest = $hold->pickup_lib;
842 $logger->info("putting hold into transit on pickup_lib update");
844 my $transit = Fieldmapper::action::hold_transit_copy->new;
845 $transit->hold($hold->id);
846 $transit->source($src);
847 $transit->dest($dest);
848 $transit->target_copy($copy->id);
849 $transit->source_send_time('now');
850 $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
852 $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
853 $copy->editor($e->requestor->id);
854 $copy->edit_date('now');
856 $e->create_action_hold_transit_copy($transit) or return $e->die_event;
857 $e->update_asset_copy($copy) or return $e->die_event;
861 # if the hold is frozen, this method ensures that the hold is not "targeted",
862 # that is, it clears the current_copy and prev_check_time to essentiallly
863 # reset the hold. If it is being activated, it runs the targeter in the background
864 sub update_hold_if_frozen {
865 my($self, $e, $hold, $orig_hold) = @_;
866 return if $hold->capture_time;
868 if($U->is_true($hold->frozen)) {
869 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
870 $hold->clear_current_copy;
871 $hold->clear_prev_check_time;
874 if($U->is_true($orig_hold->frozen)) {
875 $logger->info("Running targeter on activated hold ".$hold->id);
876 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
881 __PACKAGE__->register_method(
882 method => "hold_note_CUD",
883 api_name => "open-ils.circ.hold_request.note.cud",
885 desc => 'Create, update or delete a hold request note. If the operator (from Auth. token) '
886 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
888 { desc => 'Authentication token', type => 'string' },
889 { desc => 'Hold note object', type => 'object' }
892 desc => 'Returns the note ID, event on error'
898 my($self, $conn, $auth, $note) = @_;
900 my $e = new_editor(authtoken => $auth, xact => 1);
901 return $e->die_event unless $e->checkauth;
903 my $hold = $e->retrieve_action_hold_request($note->hold)
904 or return $e->die_event;
906 if($hold->usr ne $e->requestor->id) {
907 my $usr = $e->retrieve_actor_user($hold->usr);
908 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
909 $note->staff('t') if $note->isnew;
913 $e->create_action_hold_request_note($note) or return $e->die_event;
914 } elsif($note->ischanged) {
915 $e->update_action_hold_request_note($note) or return $e->die_event;
916 } elsif($note->isdeleted) {
917 $e->delete_action_hold_request_note($note) or return $e->die_event;
925 __PACKAGE__->register_method(
926 method => "retrieve_hold_status",
927 api_name => "open-ils.circ.hold.status.retrieve",
929 desc => 'Calculates the current status of the hold. The requestor must have ' .
930 'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
932 { desc => 'Hold ID', type => 'number' }
935 # type => 'number', # event sometimes
936 desc => <<'END_OF_DESC'
937 Returns event on error or:
938 -1 on error (for now),
939 1 for 'waiting for copy to become available',
940 2 for 'waiting for copy capture',
943 5 for 'hold-shelf-delay'
950 sub retrieve_hold_status {
951 my($self, $client, $auth, $hold_id) = @_;
953 my $e = new_editor(authtoken => $auth);
954 return $e->event unless $e->checkauth;
955 my $hold = $e->retrieve_action_hold_request($hold_id)
958 if( $e->requestor->id != $hold->usr ) {
959 return $e->event unless $e->allowed('VIEW_HOLD');
962 return _hold_status($e, $hold);
968 if ($hold->cancel_time) {
971 return 1 unless $hold->current_copy;
972 return 2 unless $hold->capture_time;
974 my $copy = $hold->current_copy;
975 unless( ref $copy ) {
976 $copy = $e->retrieve_asset_copy($hold->current_copy)
980 return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
982 if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
984 my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
985 return 4 unless $hs_wait_interval;
987 # if a hold_shelf_status_delay interval is defined and start_time plus
988 # the interval is greater than now, consider the hold to be in the virtual
989 # "on its way to the holds shelf" status. Return 5.
991 my $transit = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
992 my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
993 $start_time = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
994 my $end_time = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
996 return 5 if $end_time > DateTime->now;
1005 __PACKAGE__->register_method(
1006 method => "retrieve_hold_queue_stats",
1007 api_name => "open-ils.circ.hold.queue_stats.retrieve",
1009 desc => 'Returns summary data about the state of a hold',
1011 { desc => 'Authentication token', type => 'string'},
1012 { desc => 'Hold ID', type => 'number'},
1015 desc => q/Summary object with keys:
1016 total_holds : total holds in queue
1017 queue_position : current queue position
1018 potential_copies : number of potential copies for this hold
1019 estimated_wait : estimated wait time in days
1020 status : hold status
1021 -1 => error or unexpected state,
1022 1 => 'waiting for copy to become available',
1023 2 => 'waiting for copy capture',
1026 5 => 'hold-shelf-delay'
1033 sub retrieve_hold_queue_stats {
1034 my($self, $conn, $auth, $hold_id) = @_;
1035 my $e = new_editor(authtoken => $auth);
1036 return $e->event unless $e->checkauth;
1037 my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1038 if($e->requestor->id != $hold->usr) {
1039 return $e->event unless $e->allowed('VIEW_HOLD');
1041 return retrieve_hold_queue_status_impl($e, $hold);
1044 sub retrieve_hold_queue_status_impl {
1048 # The holds queue is defined as the distinct set of holds that share at
1049 # least one potential copy with the context hold, plus any holds that
1050 # share the same hold type and target. The latter part exists to
1051 # accomodate holds that currently have no potential copies
1052 my $q_holds = $e->json_query({
1054 # fetch cut_in_line and request_time since they're in the order_by
1055 # and we're asking for distinct values
1056 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1057 from => { ahr => 'ahcm' },
1061 "field" => "cut_in_line",
1062 "transform" => "coalesce",
1064 "direction" => "desc"
1066 { "class" => "ahr", "field" => "request_time" }
1073 select => {ahcm => ['target_copy']},
1075 where => {hold => $hold->id}
1082 if (!@$q_holds) { # none? maybe we don't have a map ...
1083 $q_holds = $e->json_query({
1084 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1089 "field" => "cut_in_line",
1090 "transform" => "coalesce",
1092 "direction" => "desc"
1094 { "class" => "ahr", "field" => "request_time" }
1097 hold_type => $hold->hold_type,
1098 target => $hold->target
1105 for my $h (@$q_holds) {
1106 last if $h->{id} == $hold->id;
1110 my $hold_data = $e->json_query({
1112 acp => [ {column => 'id', transform => 'count', aggregate => 1, alias => 'count'} ],
1113 ccm => [ {column =>'avg_wait_time'} ]
1119 ccm => {type => 'left'}
1124 where => {'+ahcm' => {hold => $hold->id} }
1127 my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1129 my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1130 my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1131 $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1132 $default_wait ||= '0 seconds';
1134 # Estimated wait time is the average wait time across the set
1135 # of potential copies, divided by the number of potential copies
1136 # times the queue position.
1138 my $combined_secs = 0;
1139 my $num_potentials = 0;
1141 for my $wait_data (@$hold_data) {
1142 my $count += $wait_data->{count};
1143 $combined_secs += $count *
1144 OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1145 $num_potentials += $count;
1148 my $estimated_wait = -1;
1150 if($num_potentials) {
1151 my $avg_wait = $combined_secs / $num_potentials;
1152 $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1153 $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1157 total_holds => scalar(@$q_holds),
1158 queue_position => $qpos,
1159 potential_copies => $num_potentials,
1160 status => _hold_status( $e, $hold ),
1161 estimated_wait => int($estimated_wait)
1166 sub fetch_open_hold_by_current_copy {
1169 my $hold = $apputils->simplereq(
1171 'open-ils.cstore.direct.action.hold_request.search.atomic',
1172 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1173 return $hold->[0] if ref($hold);
1177 sub fetch_related_holds {
1180 return $apputils->simplereq(
1182 'open-ils.cstore.direct.action.hold_request.search.atomic',
1183 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1187 __PACKAGE__->register_method(
1188 method => "hold_pull_list",
1189 api_name => "open-ils.circ.hold_pull_list.retrieve",
1191 desc => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1192 'The location is determined by the login session.',
1194 { desc => 'Limit (optional)', type => 'number'},
1195 { desc => 'Offset (optional)', type => 'number'},
1198 desc => 'reference to a list of holds, or event on failure',
1203 __PACKAGE__->register_method(
1204 method => "hold_pull_list",
1205 api_name => "open-ils.circ.hold_pull_list.id_list.retrieve",
1207 desc => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1208 'The location is determined by the login session.',
1210 { desc => 'Limit (optional)', type => 'number'},
1211 { desc => 'Offset (optional)', type => 'number'},
1214 desc => 'reference to a list of holds, or event on failure',
1219 __PACKAGE__->register_method(
1220 method => "hold_pull_list",
1221 api_name => "open-ils.circ.hold_pull_list.retrieve.count",
1223 desc => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1224 'The location is determined by the login session.',
1226 { desc => 'Limit (optional)', type => 'number'},
1227 { desc => 'Offset (optional)', type => 'number'},
1230 desc => 'Holds count (integer), or event on failure',
1237 sub hold_pull_list {
1238 my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1239 my( $reqr, $evt ) = $U->checkses($authtoken);
1240 return $evt if $evt;
1242 my $org = $reqr->ws_ou || $reqr->home_ou;
1243 # the perm locaiton shouldn't really matter here since holds
1244 # will exist all over and VIEW_HOLDS should be universal
1245 $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1246 return $evt if $evt;
1248 if($self->api_name =~ /count/) {
1250 my $count = $U->storagereq(
1251 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1252 $org, $limit, $offset );
1254 $logger->info("Grabbing pull list for org unit $org with $count items");
1257 } elsif( $self->api_name =~ /id_list/ ) {
1258 return $U->storagereq(
1259 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1260 $org, $limit, $offset );
1263 return $U->storagereq(
1264 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1265 $org, $limit, $offset );
1269 __PACKAGE__->register_method(
1270 method => "print_hold_pull_list",
1271 api_name => "open-ils.circ.hold_pull_list.print",
1273 desc => 'Returns an HTML-formatted holds pull list',
1275 { desc => 'Authtoken', type => 'string'},
1276 { desc => 'Org unit ID. Optional, defaults to workstation org unit', type => 'number'},
1279 desc => 'HTML string',
1285 sub print_hold_pull_list {
1286 my($self, $client, $auth, $org_id) = @_;
1288 my $e = new_editor(authtoken=>$auth);
1289 return $e->event unless $e->checkauth;
1291 $org_id = (defined $org_id) ? $org_id : $e->requestor->ws_ou;
1292 return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1294 my $hold_ids = $U->storagereq(
1295 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1298 return undef unless @$hold_ids;
1300 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1302 # Holds will /NOT/ be in order after this ...
1303 my $holds = $e->search_action_hold_request({id => $hold_ids}, {substream => 1});
1304 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1306 # ... so we must resort.
1307 my $hold_map = +{map { $_->id => $_ } @$holds};
1308 my $sorted_holds = [];
1309 push @$sorted_holds, $hold_map->{$_} foreach @$hold_ids;
1311 return $U->fire_object_event(
1312 undef, "ahr.format.pull_list", $sorted_holds,
1313 $org_id, undef, undef, $client
1318 __PACKAGE__->register_method(
1319 method => "print_hold_pull_list_stream",
1321 api_name => "open-ils.circ.hold_pull_list.print.stream",
1323 desc => 'Returns a stream of fleshed holds',
1325 { desc => 'Authtoken', type => 'string'},
1326 { desc => 'Hash of optional param: Org unit ID (defaults to workstation org unit), limit, offset, sort (array of: acplo.position, call_number, request_time)',
1331 desc => 'A stream of fleshed holds',
1337 sub print_hold_pull_list_stream {
1338 my($self, $client, $auth, $params) = @_;
1340 my $e = new_editor(authtoken=>$auth);
1341 return $e->die_event unless $e->checkauth;
1343 delete($$params{org_id}) unless (int($$params{org_id}));
1344 delete($$params{limit}) unless (int($$params{limit}));
1345 delete($$params{offset}) unless (int($$params{offset}));
1346 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1347 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1348 $$params{chunk_size} ||= 10;
1350 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1351 return $e->die_event unless $e->allowed('VIEW_HOLD', $$params{org_id });
1354 if ($$params{sort} && @{ $$params{sort} }) {
1355 for my $s (@{ $$params{sort} }) {
1356 if ($s eq 'acplo.position') {
1358 "class" => "acplo", "field" => "position",
1359 "transform" => "coalesce", "params" => [999]
1361 } elsif ($s eq 'call_number') {
1362 push @$sort, {"class" => "acn", "field" => "label"};
1363 } elsif ($s eq 'request_time') {
1364 push @$sort, {"class" => "ahr", "field" => "request_time"};
1368 push @$sort, {"class" => "ahr", "field" => "request_time"};
1371 my $holds_ids = $e->json_query(
1373 "select" => {"ahr" => ["id"]},
1378 "fkey" => "current_copy",
1380 "circ_lib" => $$params{org_id}, "status" => [0,7]
1385 "fkey" => "call_number"
1389 "fkey" => "circ_lib",
1392 "location" => {"=" => {"+acp" => "location"}}
1401 "capture_time" => undef,
1402 "cancel_time" => undef,
1404 {"expire_time" => undef },
1405 {"expire_time" => {">" => "now"}}
1409 (@$sort ? (order_by => $sort) : ()),
1410 ($$params{limit} ? (limit => $$params{limit}) : ()),
1411 ($$params{offset} ? (offset => $$params{offset}) : ())
1412 }, {"substream" => 1}
1413 ) or return $e->die_event;
1415 $logger->info("about to stream back " . scalar(@$holds_ids) . " holds");
1418 for my $hid (@$holds_ids) {
1419 push @chunk, $e->retrieve_action_hold_request([
1423 "ahr" => ["usr", "current_copy"],
1425 "acp" => ["location", "call_number"],
1431 if (@chunk >= $$params{chunk_size}) {
1432 $client->respond( \@chunk );
1436 $client->respond_complete( \@chunk ) if (@chunk);
1443 __PACKAGE__->register_method(
1444 method => 'fetch_hold_notify',
1445 api_name => 'open-ils.circ.hold_notification.retrieve_by_hold',
1448 Returns a list of hold notification objects based on hold id.
1449 @param authtoken The loggin session key
1450 @param holdid The id of the hold whose notifications we want to retrieve
1451 @return An array of hold notification objects, event on error.
1455 sub fetch_hold_notify {
1456 my( $self, $conn, $authtoken, $holdid ) = @_;
1457 my( $requestor, $evt ) = $U->checkses($authtoken);
1458 return $evt if $evt;
1459 my ($hold, $patron);
1460 ($hold, $evt) = $U->fetch_hold($holdid);
1461 return $evt if $evt;
1462 ($patron, $evt) = $U->fetch_user($hold->usr);
1463 return $evt if $evt;
1465 $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1466 return $evt if $evt;
1468 $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1469 return $U->cstorereq(
1470 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1474 __PACKAGE__->register_method(
1475 method => 'create_hold_notify',
1476 api_name => 'open-ils.circ.hold_notification.create',
1478 Creates a new hold notification object
1479 @param authtoken The login session key
1480 @param notification The hold notification object to create
1481 @return ID of the new object on success, Event on error
1485 sub create_hold_notify {
1486 my( $self, $conn, $auth, $note ) = @_;
1487 my $e = new_editor(authtoken=>$auth, xact=>1);
1488 return $e->die_event unless $e->checkauth;
1490 my $hold = $e->retrieve_action_hold_request($note->hold)
1491 or return $e->die_event;
1492 my $patron = $e->retrieve_actor_user($hold->usr)
1493 or return $e->die_event;
1495 return $e->die_event unless
1496 $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1498 $note->notify_staff($e->requestor->id);
1499 $e->create_action_hold_notification($note) or return $e->die_event;
1504 __PACKAGE__->register_method(
1505 method => 'create_hold_note',
1506 api_name => 'open-ils.circ.hold_note.create',
1508 Creates a new hold request note object
1509 @param authtoken The login session key
1510 @param note The hold note object to create
1511 @return ID of the new object on success, Event on error
1515 sub create_hold_note {
1516 my( $self, $conn, $auth, $note ) = @_;
1517 my $e = new_editor(authtoken=>$auth, xact=>1);
1518 return $e->die_event unless $e->checkauth;
1520 my $hold = $e->retrieve_action_hold_request($note->hold)
1521 or return $e->die_event;
1522 my $patron = $e->retrieve_actor_user($hold->usr)
1523 or return $e->die_event;
1525 return $e->die_event unless
1526 $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn. Probably want something more specific
1528 $e->create_action_hold_request_note($note) or return $e->die_event;
1533 __PACKAGE__->register_method(
1534 method => 'reset_hold',
1535 api_name => 'open-ils.circ.hold.reset',
1537 Un-captures and un-targets a hold, essentially returning
1538 it to the state it was in directly after it was placed,
1539 then attempts to re-target the hold
1540 @param authtoken The login session key
1541 @param holdid The id of the hold
1547 my( $self, $conn, $auth, $holdid ) = @_;
1549 my ($hold, $evt) = $U->fetch_hold($holdid);
1550 return $evt if $evt;
1551 ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1552 return $evt if $evt;
1553 $evt = _reset_hold($self, $reqr, $hold);
1554 return $evt if $evt;
1559 __PACKAGE__->register_method(
1560 method => 'reset_hold_batch',
1561 api_name => 'open-ils.circ.hold.reset.batch'
1564 sub reset_hold_batch {
1565 my($self, $conn, $auth, $hold_ids) = @_;
1567 my $e = new_editor(authtoken => $auth);
1568 return $e->event unless $e->checkauth;
1570 for my $hold_id ($hold_ids) {
1572 my $hold = $e->retrieve_action_hold_request(
1573 [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}])
1574 or return $e->event;
1576 next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1577 _reset_hold($self, $e->requestor, $hold);
1585 my ($self, $reqr, $hold) = @_;
1587 my $e = new_editor(xact =>1, requestor => $reqr);
1589 $logger->info("reseting hold ".$hold->id);
1591 my $hid = $hold->id;
1593 if( $hold->capture_time and $hold->current_copy ) {
1595 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1596 or return $e->die_event;
1598 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1599 $logger->info("setting copy to status 'reshelving' on hold retarget");
1600 $copy->status(OILS_COPY_STATUS_RESHELVING);
1601 $copy->editor($e->requestor->id);
1602 $copy->edit_date('now');
1603 $e->update_asset_copy($copy) or return $e->die_event;
1605 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1607 # We don't want the copy to remain "in transit"
1608 $copy->status(OILS_COPY_STATUS_RESHELVING);
1609 $logger->warn("! reseting hold [$hid] that is in transit");
1610 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1613 my $trans = $e->retrieve_action_transit_copy($transid);
1615 $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1616 my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1);
1617 $logger->info("Transit abort completed with result $evt");
1618 unless ("$evt" eq 1) {
1627 $hold->clear_capture_time;
1628 $hold->clear_current_copy;
1629 $hold->clear_shelf_time;
1630 $hold->clear_shelf_expire_time;
1632 $e->update_action_hold_request($hold) or return $e->die_event;
1636 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1642 __PACKAGE__->register_method(
1643 method => 'fetch_open_title_holds',
1644 api_name => 'open-ils.circ.open_holds.retrieve',
1646 Returns a list ids of un-fulfilled holds for a given title id
1647 @param authtoken The login session key
1648 @param id the id of the item whose holds we want to retrieve
1649 @param type The hold type - M, T, I, V, C, F, R
1653 sub fetch_open_title_holds {
1654 my( $self, $conn, $auth, $id, $type, $org ) = @_;
1655 my $e = new_editor( authtoken => $auth );
1656 return $e->event unless $e->checkauth;
1659 $org ||= $e->requestor->ws_ou;
1661 # return $e->search_action_hold_request(
1662 # { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1664 # XXX make me return IDs in the future ^--
1665 my $holds = $e->search_action_hold_request(
1668 cancel_time => undef,
1670 fulfillment_time => undef
1674 flesh_hold_transits($holds);
1679 sub flesh_hold_transits {
1681 for my $hold ( @$holds ) {
1683 $apputils->simplereq(
1685 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1686 { hold => $hold->id },
1687 { order_by => { ahtc => 'id desc' }, limit => 1 }
1693 sub flesh_hold_notices {
1694 my( $holds, $e ) = @_;
1695 $e ||= new_editor();
1697 for my $hold (@$holds) {
1698 my $notices = $e->search_action_hold_notification(
1700 { hold => $hold->id },
1701 { order_by => { anh => 'notify_time desc' } },
1706 $hold->notify_count(scalar(@$notices));
1708 my $n = $e->retrieve_action_hold_notification($$notices[0])
1709 or return $e->event;
1710 $hold->notify_time($n->notify_time);
1716 __PACKAGE__->register_method(
1717 method => 'fetch_captured_holds',
1718 api_name => 'open-ils.circ.captured_holds.on_shelf.retrieve',
1721 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
1722 @param authtoken The login session key
1723 @param org The org id of the location in question
1727 __PACKAGE__->register_method(
1728 method => 'fetch_captured_holds',
1729 api_name => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
1732 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
1733 @param authtoken The login session key
1734 @param org The org id of the location in question
1738 __PACKAGE__->register_method(
1739 method => 'fetch_captured_holds',
1740 api_name => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
1743 Returns list ids of shelf-expired un-fulfilled holds for a given title id
1744 @param authtoken The login session key
1745 @param org The org id of the location in question
1750 sub fetch_captured_holds {
1751 my( $self, $conn, $auth, $org ) = @_;
1753 my $e = new_editor(authtoken => $auth);
1754 return $e->die_event unless $e->checkauth;
1755 return $e->die_event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
1757 $org ||= $e->requestor->ws_ou;
1760 select => { ahr => ['id'] },
1765 fkey => 'current_copy'
1770 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
1772 capture_time => { "!=" => undef },
1773 current_copy => { "!=" => undef },
1774 fulfillment_time => undef,
1776 cancel_time => undef,
1780 if($self->api_name =~ /expired/) {
1781 $query->{'where'}->{'+ahr'}->{'shelf_expire_time'} = {'<' => 'now'};
1782 $query->{'where'}->{'+ahr'}->{'shelf_time'} = {'!=' => undef};
1784 my $hold_ids = $e->json_query( $query );
1786 for my $hold_id (@$hold_ids) {
1787 if($self->api_name =~ /id_list/) {
1788 $conn->respond($hold_id->{id});
1792 $e->retrieve_action_hold_request([
1796 flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
1797 order_by => {anh => 'notify_time desc'}
1807 __PACKAGE__->register_method(
1808 method => "print_expired_holds_stream",
1809 api_name => "open-ils.circ.captured_holds.expired.print.stream",
1813 sub print_expired_holds_stream {
1814 my ($self, $client, $auth, $params) = @_;
1816 # No need to check specific permissions: we're going to call another method
1817 # that will do that.
1818 my $e = new_editor("authtoken" => $auth);
1819 return $e->die_event unless $e->checkauth;
1821 delete($$params{org_id}) unless (int($$params{org_id}));
1822 delete($$params{limit}) unless (int($$params{limit}));
1823 delete($$params{offset}) unless (int($$params{offset}));
1824 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1825 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1826 $$params{chunk_size} ||= 10;
1828 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1830 my @hold_ids = $self->method_lookup(
1831 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
1832 )->run($auth, $params->{"org_id"});
1837 } elsif (defined $U->event_code($hold_ids[0])) {
1839 return $hold_ids[0];
1842 $logger->info("about to stream back up to " . scalar(@hold_ids) . " expired holds");
1845 my @hid_chunk = splice @hold_ids, 0, $params->{"chunk_size"};
1847 my $result_chunk = $e->json_query({
1849 "acp" => ["barcode"],
1851 first_given_name second_given_name family_name alias
1860 "field" => "id", "fkey" => "current_copy",
1863 "field" => "id", "fkey" => "call_number",
1866 "field" => "id", "fkey" => "record"
1870 "acpl" => {"field" => "id", "fkey" => "location"}
1873 "au" => {"field" => "id", "fkey" => "usr"}
1876 "where" => {"+ahr" => {"id" => \@hid_chunk}}
1877 }) or return $e->die_event;
1878 $client->respond($result_chunk);
1885 __PACKAGE__->register_method(
1886 method => "check_title_hold_batch",
1887 api_name => "open-ils.circ.title_hold.is_possible.batch",
1890 desc => '@see open-ils.circ.title_hold.is_possible.batch',
1892 { desc => 'Authentication token', type => 'string'},
1893 { desc => 'Array of Hash of named parameters', type => 'array'},
1896 desc => 'Array of response objects',
1902 sub check_title_hold_batch {
1903 my($self, $client, $authtoken, $param_list) = @_;
1904 foreach (@$param_list) {
1905 my ($res) = $self->method_lookup('open-ils.circ.title_hold.is_possible')->run($authtoken, $_);
1906 $client->respond($res);
1912 __PACKAGE__->register_method(
1913 method => "check_title_hold",
1914 api_name => "open-ils.circ.title_hold.is_possible",
1916 desc => 'Determines if a hold were to be placed by a given user, ' .
1917 'whether or not said hold would have any potential copies to fulfill it.' .
1918 'The named paramaters of the second argument include: ' .
1919 'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
1920 'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' ,
1922 { desc => 'Authentication token', type => 'string'},
1923 { desc => 'Hash of named parameters', type => 'object'},
1926 desc => 'List of new message IDs (empty if none)',
1932 =head3 check_title_hold (token, hash)
1934 The named fields in the hash are:
1936 patronid - ID of the hold recipient (required)
1937 depth - hold range depth (default 0)
1938 pickup_lib - destination for hold, fallback value for selection_ou
1939 selection_ou - ID of org_unit establishing hard and soft hold boundary settings
1940 issuanceid - ID of the issuance to be held, required for Issuance level hold
1941 titleid - ID (BRN) of the title to be held, required for Title level hold
1942 volume_id - required for Volume level hold
1943 copy_id - required for Copy level hold
1944 mrid - required for Meta-record level hold
1945 hold_type - T, C (or R or F), I, V or M for Title, Copy, Issuance, Volume or Meta-record (default "T")
1947 All key/value pairs are passed on to do_possibility_checks.
1951 # FIXME: better params checking. what other params are required, if any?
1952 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
1953 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still
1954 # used in conditionals, where it may be undefined, causing a warning.
1955 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
1957 sub check_title_hold {
1958 my( $self, $client, $authtoken, $params ) = @_;
1959 my $e = new_editor(authtoken=>$authtoken);
1960 return $e->event unless $e->checkauth;
1962 my %params = %$params;
1963 my $depth = $params{depth} || 0;
1964 my $selection_ou = $params{selection_ou} || $params{pickup_lib};
1966 my $patron = $e->retrieve_actor_user($params{patronid})
1967 or return $e->event;
1969 if( $e->requestor->id ne $patron->id ) {
1970 return $e->event unless
1971 $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
1974 return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
1976 my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
1977 or return $e->event;
1979 my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
1980 my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
1983 my $return_depth = $hard_boundary; # default depth to return on success
1984 if(defined $soft_boundary and $depth < $soft_boundary) {
1985 # work up the tree and as soon as we find a potential copy, use that depth
1986 # also, make sure we don't go past the hard boundary if it exists
1988 # our min boundary is the greater of user-specified boundary or hard boundary
1989 my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?
1990 $hard_boundary : $depth;
1992 my $depth = $soft_boundary;
1993 while($depth >= $min_depth) {
1994 $logger->info("performing hold possibility check with soft boundary $depth");
1995 @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
1997 $return_depth = $depth;
2002 } elsif(defined $hard_boundary and $depth < $hard_boundary) {
2003 # there is no soft boundary, enforce the hard boundary if it exists
2004 $logger->info("performing hold possibility check with hard boundary $hard_boundary");
2005 @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
2007 # no boundaries defined, fall back to user specifed boundary or no boundary
2008 $logger->info("performing hold possibility check with no boundary");
2009 @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
2015 "depth" => $return_depth,
2016 "local_avail" => $status[1]
2018 } elsif ($status[2]) {
2019 my $n = scalar @{$status[2]};
2020 return {"success" => 0, "last_event" => $status[2]->[$n - 1]};
2022 return {"success" => 0};
2028 sub do_possibility_checks {
2029 my($e, $patron, $request_lib, $depth, %params) = @_;
2031 my $issuanceid = $params{issuanceid} || "";
2032 my $titleid = $params{titleid} || "";
2033 my $volid = $params{volume_id};
2034 my $copyid = $params{copy_id};
2035 my $mrid = $params{mrid} || "";
2036 my $pickup_lib = $params{pickup_lib};
2037 my $hold_type = $params{hold_type} || 'T';
2038 my $selection_ou = $params{selection_ou} || $pickup_lib;
2045 if( $hold_type eq OILS_HOLD_TYPE_FORCE || $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_COPY ) {
2047 return $e->event unless $copy = $e->retrieve_asset_copy($copyid);
2048 return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
2049 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2051 return verify_copy_for_hold(
2052 $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib
2055 } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2057 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
2058 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2060 return _check_volume_hold_is_possible(
2061 $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2064 } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
2066 return _check_title_hold_is_possible(
2067 $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2070 } elsif( $hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2072 return _check_issuance_hold_is_possible(
2073 $issuanceid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2076 } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2078 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
2079 my @recs = map { $_->source } @$maps;
2081 for my $rec (@recs) {
2082 @status = _check_title_hold_is_possible(
2083 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2089 # else { Unrecognized hold_type ! } # FIXME: return error? or 0?
2093 sub create_ranged_org_filter {
2094 my($e, $selection_ou, $depth) = @_;
2096 # find the orgs from which this hold may be fulfilled,
2097 # based on the selection_ou and depth
2099 my $top_org = $e->search_actor_org_unit([
2100 {parent_ou => undef},
2101 {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
2104 return () if $depth == $top_org->ou_type->depth;
2106 my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
2107 %org_filter = (circ_lib => []);
2108 push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
2110 $logger->info("hold org filter at depth $depth and selection_ou ".
2111 "$selection_ou created list of @{$org_filter{circ_lib}}");
2117 sub _check_title_hold_is_possible {
2118 my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2120 my $e = new_editor();
2121 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2123 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2124 my $copies = $e->json_query(
2126 select => { acp => ['id', 'circ_lib'] },
2131 fkey => 'call_number',
2135 filter => { id => $titleid },
2140 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2141 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2145 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2150 $logger->info("title possible found ".scalar(@$copies)." potential copies");
2154 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2155 "payload" => {"fail_part" => "no_ultimate_items"}
2160 # -----------------------------------------------------------------------
2161 # sort the copies into buckets based on their circ_lib proximity to
2162 # the patron's home_ou.
2163 # -----------------------------------------------------------------------
2165 my $home_org = $patron->home_ou;
2166 my $req_org = $request_lib->id;
2168 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2170 $prox_cache{$home_org} =
2171 $e->search_actor_org_unit_proximity({from_org => $home_org})
2172 unless $prox_cache{$home_org};
2173 my $home_prox = $prox_cache{$home_org};
2176 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2177 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2179 my @keys = sort { $a <=> $b } keys %buckets;
2182 if( $home_org ne $req_org ) {
2183 # -----------------------------------------------------------------------
2184 # shove the copies close to the request_lib into the primary buckets
2185 # directly before the farthest away copies. That way, they are not
2186 # given priority, but they are checked before the farthest copies.
2187 # -----------------------------------------------------------------------
2188 $prox_cache{$req_org} =
2189 $e->search_actor_org_unit_proximity({from_org => $req_org})
2190 unless $prox_cache{$req_org};
2191 my $req_prox = $prox_cache{$req_org};
2194 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2195 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2197 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2198 my $new_key = $highest_key - 0.5; # right before the farthest prox
2199 my @keys2 = sort { $a <=> $b } keys %buckets2;
2200 for my $key (@keys2) {
2201 last if $key >= $highest_key;
2202 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2206 @keys = sort { $a <=> $b } keys %buckets;
2211 OUTER: for my $key (@keys) {
2212 my @cps = @{$buckets{$key}};
2214 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2216 for my $copyid (@cps) {
2218 next if $seen{$copyid};
2219 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2220 my $copy = $e->retrieve_asset_copy($copyid);
2221 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2223 unless($title) { # grab the title if we don't already have it
2224 my $vol = $e->retrieve_asset_call_number(
2225 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2226 $title = $vol->record;
2229 @status = verify_copy_for_hold(
2230 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2232 last OUTER if $status[0];
2239 sub _check_issuance_hold_is_possible {
2240 my( $issuanceid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2242 my $e = new_editor();
2243 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2245 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2246 my $copies = $e->json_query(
2248 select => { acp => ['id', 'circ_lib'] },
2254 filter => { issuance => $issuanceid }
2256 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2257 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2261 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2267 $logger->info("issuance possible found ".scalar(@$copies)." potential copies");
2271 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2272 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2277 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2278 "payload" => {"fail_part" => "no_ultimate_items"}
2286 # -----------------------------------------------------------------------
2287 # sort the copies into buckets based on their circ_lib proximity to
2288 # the patron's home_ou.
2289 # -----------------------------------------------------------------------
2291 my $home_org = $patron->home_ou;
2292 my $req_org = $request_lib->id;
2294 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2296 $prox_cache{$home_org} =
2297 $e->search_actor_org_unit_proximity({from_org => $home_org})
2298 unless $prox_cache{$home_org};
2299 my $home_prox = $prox_cache{$home_org};
2302 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2303 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2305 my @keys = sort { $a <=> $b } keys %buckets;
2308 if( $home_org ne $req_org ) {
2309 # -----------------------------------------------------------------------
2310 # shove the copies close to the request_lib into the primary buckets
2311 # directly before the farthest away copies. That way, they are not
2312 # given priority, but they are checked before the farthest copies.
2313 # -----------------------------------------------------------------------
2314 $prox_cache{$req_org} =
2315 $e->search_actor_org_unit_proximity({from_org => $req_org})
2316 unless $prox_cache{$req_org};
2317 my $req_prox = $prox_cache{$req_org};
2320 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2321 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2323 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2324 my $new_key = $highest_key - 0.5; # right before the farthest prox
2325 my @keys2 = sort { $a <=> $b } keys %buckets2;
2326 for my $key (@keys2) {
2327 last if $key >= $highest_key;
2328 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2332 @keys = sort { $a <=> $b } keys %buckets;
2337 OUTER: for my $key (@keys) {
2338 my @cps = @{$buckets{$key}};
2340 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2342 for my $copyid (@cps) {
2344 next if $seen{$copyid};
2345 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2346 my $copy = $e->retrieve_asset_copy($copyid);
2347 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2349 unless($title) { # grab the title if we don't already have it
2350 my $vol = $e->retrieve_asset_call_number(
2351 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2352 $title = $vol->record;
2355 @status = verify_copy_for_hold(
2356 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2358 last OUTER if $status[0];
2363 if (!defined($empty_ok)) {
2364 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2365 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2368 return (1,0) if ($empty_ok);
2374 sub _check_volume_hold_is_possible {
2375 my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2376 my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
2377 my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
2378 $logger->info("checking possibility of volume hold for volume ".$vol->id);
2383 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2384 "payload" => {"fail_part" => "no_ultimate_items"}
2390 for my $copy ( @$copies ) {
2391 @status = verify_copy_for_hold(
2392 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
2400 sub verify_copy_for_hold {
2401 my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib ) = @_;
2402 $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
2403 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2404 { patron => $patron,
2405 requestor => $requestor,
2408 title_descriptor => $title->fixed_fields, # this is fleshed into the title object
2409 pickup_lib => $pickup_lib,
2410 request_lib => $request_lib,
2412 show_event_list => 1
2417 (not scalar @$permitted), # true if permitted is an empty arrayref
2419 ($copy->circ_lib == $pickup_lib) and
2420 ($copy->status == OILS_COPY_STATUS_AVAILABLE)
2428 sub find_nearest_permitted_hold {
2431 my $editor = shift; # CStoreEditor object
2432 my $copy = shift; # copy to target
2433 my $user = shift; # staff
2434 my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
2436 my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
2438 my $bc = $copy->barcode;
2440 # find any existing holds that already target this copy
2441 my $old_holds = $editor->search_action_hold_request(
2442 { current_copy => $copy->id,
2443 cancel_time => undef,
2444 capture_time => undef
2448 # hold->type "R" means we need this copy
2449 for my $h (@$old_holds) { return ($h) if $h->hold_type eq 'R'; }
2452 my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
2454 $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
2455 " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
2457 my $fifo = $U->ou_ancestor_setting_value($user->ws_ou, 'circ.holds_fifo');
2459 # search for what should be the best holds for this copy to fulfill
2460 my $best_holds = $U->storagereq_xact(
2461 "open-ils.storage.action.hold_request.nearest_hold.atomic",
2462 $user->ws_ou, $copy->id, 10, $hold_stall_interval, $fifo );
2464 unless(@$best_holds) {
2466 if( my $hold = $$old_holds[0] ) {
2467 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2471 $logger->info("circulator: no suitable holds found for copy $bc");
2472 return (undef, $evt);
2478 # for each potential hold, we have to run the permit script
2479 # to make sure the hold is actually permitted.
2480 for my $holdid (@$best_holds) {
2481 next unless $holdid;
2482 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
2484 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
2485 my $reqr = $editor->retrieve_actor_user($hold->requestor) or next;
2486 my $rlib = $editor->retrieve_actor_org_unit($hold->request_lib) or next;
2488 # see if this hold is permitted
2489 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2490 { patron_id => $hold->usr,
2493 pickup_lib => $hold->pickup_lib,
2494 request_lib => $rlib,
2506 unless( $best_hold ) { # no "good" permitted holds were found
2507 if( my $hold = $$old_holds[0] ) { # can we return a pre-targeted hold?
2508 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2513 $logger->info("circulator: no suitable holds found for copy $bc");
2514 return (undef, $evt);
2517 $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
2519 # indicate a permitted hold was found
2520 return $best_hold if $check_only;
2522 # we've found a permitted hold. we need to "grab" the copy
2523 # to prevent re-targeted holds (next part) from re-grabbing the copy
2524 $best_hold->current_copy($copy->id);
2525 $editor->update_action_hold_request($best_hold)
2526 or return (undef, $editor->event);
2531 # re-target any other holds that already target this copy
2532 for my $old_hold (@$old_holds) {
2533 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
2534 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
2535 $old_hold->id." after a better hold [".$best_hold->id."] was found");
2536 $old_hold->clear_current_copy;
2537 $old_hold->clear_prev_check_time;
2538 $editor->update_action_hold_request($old_hold)
2539 or return (undef, $editor->event);
2540 push(@retarget, $old_hold->id);
2543 return ($best_hold, undef, (@retarget) ? \@retarget : undef);
2551 __PACKAGE__->register_method(
2552 method => 'all_rec_holds',
2553 api_name => 'open-ils.circ.holds.retrieve_all_from_title',
2557 my( $self, $conn, $auth, $title_id, $args ) = @_;
2559 my $e = new_editor(authtoken=>$auth);
2560 $e->checkauth or return $e->event;
2561 $e->allowed('VIEW_HOLD') or return $e->event;
2564 $args->{fulfillment_time} = undef; # we don't want to see old fulfilled holds
2565 $args->{cancel_time} = undef;
2567 my $resp = { volume_holds => [], copy_holds => [], metarecord_holds => [] };
2569 my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
2571 $resp->{metarecord_holds} = $e->search_action_hold_request(
2572 { hold_type => OILS_HOLD_TYPE_METARECORD,
2573 target => $mr_map->metarecord,
2579 $resp->{title_holds} = $e->search_action_hold_request(
2581 hold_type => OILS_HOLD_TYPE_TITLE,
2582 target => $title_id,
2586 my $vols = $e->search_asset_call_number(
2587 { record => $title_id, deleted => 'f' }, {idlist=>1});
2589 return $resp unless @$vols;
2591 $resp->{volume_holds} = $e->search_action_hold_request(
2593 hold_type => OILS_HOLD_TYPE_VOLUME,
2598 my $copies = $e->search_asset_copy(
2599 { call_number => $vols, deleted => 'f' }, {idlist=>1});
2601 return $resp unless @$copies;
2603 $resp->{copy_holds} = $e->search_action_hold_request(
2605 hold_type => OILS_HOLD_TYPE_COPY,
2617 __PACKAGE__->register_method(
2618 method => 'uber_hold',
2620 api_name => 'open-ils.circ.hold.details.retrieve'
2624 my($self, $client, $auth, $hold_id) = @_;
2625 my $e = new_editor(authtoken=>$auth);
2626 $e->checkauth or return $e->event;
2627 return uber_hold_impl($e, $hold_id);
2630 __PACKAGE__->register_method(
2631 method => 'batch_uber_hold',
2634 api_name => 'open-ils.circ.hold.details.batch.retrieve'
2637 sub batch_uber_hold {
2638 my($self, $client, $auth, $hold_ids) = @_;
2639 my $e = new_editor(authtoken=>$auth);
2640 $e->checkauth or return $e->event;
2641 $client->respond(uber_hold_impl($e, $_)) for @$hold_ids;
2645 sub uber_hold_impl {
2646 my($e, $hold_id) = @_;
2650 my $hold = $e->retrieve_action_hold_request(
2655 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
2658 ) or return $e->event;
2660 if($hold->usr->id ne $e->requestor->id) {
2661 # A user is allowed to see his/her own holds
2662 $e->allowed('VIEW_HOLD') or return $e->event;
2663 $hold->notes( # filter out any non-staff ("private") notes
2664 [ grep { !$U->is_true($_->staff) } @{$hold->notes} ] );
2667 # caller is asking for own hold, but may not have permission to view staff notes
2668 unless($e->allowed('VIEW_HOLD')) {
2669 $hold->notes( # filter out any staff notes
2670 [ grep { $U->is_true($_->staff) } @{$hold->notes} ] );
2674 my $user = $hold->usr;
2675 $hold->usr($user->id);
2677 my $card = $e->retrieve_actor_card($user->card)
2678 or return $e->event;
2680 my( $mvr, $volume, $copy ) = find_hold_mvr($e, $hold);
2682 flesh_hold_notices([$hold], $e);
2683 flesh_hold_transits([$hold]);
2685 my $details = retrieve_hold_queue_status_impl($e, $hold);
2692 patron_first => $user->first_given_name,
2693 patron_last => $user->family_name,
2694 patron_barcode => $card->barcode,
2695 patron_alias => $user->alias,
2702 # -----------------------------------------------------
2703 # Returns the MVR object that represents what the
2705 # -----------------------------------------------------
2707 my( $e, $hold ) = @_;
2714 if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2715 my $mr = $e->retrieve_metabib_metarecord($hold->target)
2716 or return $e->event;
2717 $tid = $mr->master_record;
2719 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
2720 $tid = $hold->target;
2722 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2723 $volume = $e->retrieve_asset_call_number($hold->target)
2724 or return $e->event;
2725 $tid = $volume->record;
2727 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2728 $issuance = $e->retrieve_serial_issuance([
2730 {flesh => 1, flesh_fields => {siss => [ qw/subscription/ ]}}
2731 ]) or return $e->event;
2733 $tid = $issuance->subscription->record_entry;
2735 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_COPY ) {
2736 $copy = $e->retrieve_asset_copy([
2738 {flesh => 1, flesh_fields => {acp => ['call_number']}}
2739 ]) or return $e->event;
2741 $volume = $copy->call_number;
2742 $tid = $volume->record;
2745 if(!$copy and ref $hold->current_copy ) {
2746 $copy = $hold->current_copy;
2747 $hold->current_copy($copy->id);
2750 if(!$volume and $copy) {
2751 $volume = $e->retrieve_asset_call_number($copy->call_number);
2754 # TODO return metarcord mvr for M holds
2755 my $title = $e->retrieve_biblio_record_entry($tid);
2756 return ( $U->record_to_mvr($title), $volume, $copy, $issuance );
2759 __PACKAGE__->register_method(
2760 method => 'clear_shelf_cache',
2761 api_name => 'open-ils.circ.hold.clear_shelf.get_cache',
2765 Returns the holds processed with the given cache key
2770 sub clear_shelf_cache {
2771 my($self, $client, $auth, $cache_key, $chunk_size) = @_;
2772 my $e = new_editor(authtoken => $auth, xact => 1);
2773 return $e->die_event unless $e->checkauth and $e->allowed('VIEW_HOLD');
2776 my $hold_data = OpenSRF::Utils::Cache->new('global')->get_cache($cache_key);
2779 $logger->info("no hold data found in cache"); # XXX TODO return event
2785 foreach (keys %$hold_data) {
2786 $maximum += scalar(@{ $hold_data->{$_} });
2788 $client->respond({"maximum" => $maximum, "progress" => 0});
2790 for my $action (sort keys %$hold_data) {
2791 while (@{$hold_data->{$action}}) {
2792 my @hid_chunk = splice @{$hold_data->{$action}}, 0, $chunk_size;
2794 my $result_chunk = $e->json_query({
2796 "acp" => ["barcode"],
2798 first_given_name second_given_name family_name alias
2808 "field" => "id", "fkey" => "current_copy",
2811 "field" => "id", "fkey" => "call_number",
2814 "field" => "id", "fkey" => "record"
2818 "acpl" => {"field" => "id", "fkey" => "location"}
2821 "au" => {"field" => "id", "fkey" => "usr"}
2824 "where" => {"+ahr" => {"id" => \@hid_chunk}}
2825 }, {"substream" => 1}) or return $e->die_event;
2829 +{"action" => $action, "hold_details" => $_}
2840 __PACKAGE__->register_method(
2841 method => 'clear_shelf_process',
2843 api_name => 'open-ils.circ.hold.clear_shelf.process',
2846 1. Find all holds that have expired on the holds shelf
2848 3. If a clear-shelf status is configured, put targeted copies into this status
2849 4. Divide copies into 3 groups: items to transit, items to reshelve, and items
2850 that are needed for holds. No subsequent action is taken on the holds
2851 or items after grouping.
2856 sub clear_shelf_process {
2857 my($self, $client, $auth, $org_id) = @_;
2859 my $e = new_editor(authtoken=>$auth, xact => 1);
2860 $e->checkauth or return $e->die_event;
2861 my $cache = OpenSRF::Utils::Cache->new('global');
2863 $org_id ||= $e->requestor->ws_ou;
2864 $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
2866 my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
2868 # Find holds on the shelf that have been there too long
2869 my $hold_ids = $e->search_action_hold_request(
2870 { shelf_expire_time => {'<' => 'now'},
2871 pickup_lib => $org_id,
2872 cancel_time => undef,
2873 fulfillment_time => undef,
2874 shelf_time => {'!=' => undef},
2875 capture_time => {'!=' => undef},
2876 current_copy => {'!=' => undef},
2882 my $chunk_size = 25; # chunked status updates
2884 for my $hold_id (@$hold_ids) {
2886 $logger->info("Clear shelf processing hold $hold_id");
2888 my $hold = $e->retrieve_action_hold_request([
2891 flesh_fields => {ahr => ['current_copy']}
2895 $hold->cancel_time('now');
2896 $hold->cancel_cause(2); # Hold Shelf expiration
2897 $e->update_action_hold_request($hold) or return $e->die_event;
2899 my $copy = $hold->current_copy;
2901 if($copy_status or $copy_status == 0) {
2902 # if a clear-shelf copy status is defined, update the copy
2903 $copy->status($copy_status);
2904 $copy->edit_date('now');
2905 $copy->editor($e->requestor->id);
2906 $e->update_asset_copy($copy) or return $e->die_event;
2909 push(@holds, $hold);
2910 $client->respond({maximum => scalar(@holds), progress => $counter}) if ( (++$counter % $chunk_size) == 0);
2921 for my $hold (@holds) {
2923 my $copy = $hold->current_copy;
2924 my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
2928 push(@{$cache_data{hold}}, $hold->id); # copy is needed for a hold
2930 } elsif($copy->circ_lib != $e->requestor->ws_ou) {
2932 push(@{$cache_data{transit}}, $hold->id); # copy needs to transit
2936 push(@{$cache_data{shelf}}, $hold->id); # copy needs to go back to the shelf
2940 my $cache_key = md5_hex(time . $$ . rand());
2941 $logger->info("clear_shelf_cache: storing under $cache_key");
2942 $cache->put_cache($cache_key, \%cache_data, 7200); # TODO: 2 hours. configurable?
2944 # tell the client we're done
2945 $client->respond_complete({cache_key => $cache_key});
2947 # fire off the hold cancelation trigger and wait for response so don't flood the service
2948 $U->create_events_for_hook(
2949 'hold_request.cancel.expire_holds_shelf',
2950 $_, $org_id, undef, undef, 1) for @holds;
2953 # tell the client we're done
2954 $client->respond_complete;
2958 __PACKAGE__->register_method(
2959 method => 'usr_hold_summary',
2960 api_name => 'open-ils.circ.holds.user_summary',
2962 Returns a summary of holds statuses for a given user
2966 sub usr_hold_summary {
2967 my($self, $conn, $auth, $user_id) = @_;
2969 my $e = new_editor(authtoken=>$auth);
2970 $e->checkauth or return $e->event;
2971 $e->allowed('VIEW_HOLD') or return $e->event;
2973 my $holds = $e->search_action_hold_request(
2976 fulfillment_time => undef,
2977 cancel_time => undef,
2981 my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
2982 $summary{_hold_status($e, $_)} += 1 for @$holds;
2988 __PACKAGE__->register_method(
2989 method => 'hold_has_copy_at',
2990 api_name => 'open-ils.circ.hold.has_copy_at',
2993 'Returns the ID of the found copy and name of the shelving location if there is ' .
2994 'an available copy at the specified org unit. Returns empty hash otherwise. ' .
2995 'The anticipated use for this method is to determine whether an item is ' .
2996 'available at the library where the user is placing the hold (or, alternatively, '.
2997 'at the pickup library) to encourage bypassing the hold placement and just ' .
2998 'checking out the item.' ,
3000 { desc => 'Authentication Token', type => 'string' },
3001 { desc => 'Method Arguments. Options include: hold_type, hold_target, org_unit. '
3002 . 'hold_type is the hold type code (T, V, C, M, ...). '
3003 . 'hold_target is the identifier of the hold target object. '
3004 . 'org_unit is org unit ID.',
3009 desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
3015 sub hold_has_copy_at {
3016 my($self, $conn, $auth, $args) = @_;
3018 my $e = new_editor(authtoken=>$auth);
3019 $e->checkauth or return $e->event;
3021 my $hold_type = $$args{hold_type};
3022 my $hold_target = $$args{hold_target};
3023 my $org_unit = $$args{org_unit};
3026 select => {acp => ['id'], acpl => ['name']},
3029 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
3030 ccs => {field => 'id', filter => { holdable => 't'}, fkey => 'status' }
3033 where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit}},
3037 if($hold_type eq 'C') {
3039 $query->{where}->{'+acp'}->{id} = $hold_target;
3041 } elsif($hold_type eq 'V') {
3043 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3045 } elsif($hold_type eq 'T') {
3047 $query->{from}->{acp}->{acn} = {
3049 fkey => 'call_number',
3053 filter => {id => $hold_target},
3061 $query->{from}->{acp}->{acn} = {
3063 fkey => 'call_number',
3072 filter => {metarecord => $hold_target},
3080 my $res = $e->json_query($query)->[0] or return {};
3081 return {copy => $res->{id}, location => $res->{name}} if $res;
3085 # returns true if the user already has an item checked out
3086 # that could be used to fulfill the requested hold.
3087 sub hold_item_is_checked_out {
3088 my($e, $user_id, $hold_type, $hold_target) = @_;
3091 select => {acp => ['id']},
3092 from => {acp => {}},
3096 in => { # copies for circs the user has checked out
3097 select => {circ => ['target_copy']},
3101 checkin_time => undef,
3103 {stop_fines => ["MAXFINES","LONGOVERDUE"]},
3104 {stop_fines => undef}
3114 if($hold_type eq 'C' || $hold_type eq 'R' || $hold_type eq 'F') {
3116 $query->{where}->{'+acp'}->{id}->{in}->{where}->{'target_copy'} = $hold_target;
3118 } elsif($hold_type eq 'V') {
3120 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3122 } elsif($hold_type eq 'I') {
3124 $query->{from}->{acp}->{sitem} = {
3127 filter => {issuance => $hold_target},
3130 } elsif($hold_type eq 'T') {
3132 $query->{from}->{acp}->{acn} = {
3134 fkey => 'call_number',
3138 filter => {id => $hold_target},
3146 $query->{from}->{acp}->{acn} = {
3148 fkey => 'call_number',
3157 filter => {metarecord => $hold_target},
3165 return $e->json_query($query)->[0];
3168 __PACKAGE__->register_method(
3169 method => 'change_hold_title',
3170 api_name => 'open-ils.circ.hold.change_title',
3173 Updates all title level holds targeting the specified bibs to point a new bib./,
3175 { desc => 'Authentication Token', type => 'string' },
3176 { desc => 'New Target Bib Id', type => 'number' },
3177 { desc => 'Old Target Bib Ids', type => 'array' },
3179 return => { desc => '1 on success' }
3183 sub change_hold_title {
3184 my( $self, $client, $auth, $new_bib_id, $bib_ids ) = @_;
3186 my $e = new_editor(authtoken=>$auth, xact=>1);
3187 return $e->die_event unless $e->checkauth;
3189 my $holds = $e->search_action_hold_request(
3192 cancel_time => undef,
3193 fulfillment_time => undef,
3199 flesh_fields => { ahr => ['usr'] }
3205 for my $hold (@$holds) {
3206 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3207 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3208 $hold->target( $new_bib_id );
3209 $e->update_action_hold_request($hold) or return $e->die_event;
3218 __PACKAGE__->register_method(
3219 method => 'rec_hold_count',
3220 api_name => 'open-ils.circ.bre.holds.count',
3222 desc => q/Returns the total number of holds that target the
3223 selected bib record or its associated copies and call_numbers/,
3225 { desc => 'Bib ID', type => 'number' },
3227 return => {desc => 'Hold count', type => 'number'}
3231 __PACKAGE__->register_method(
3232 method => 'rec_hold_count',
3233 api_name => 'open-ils.circ.mmr.holds.count',
3235 desc => q/Returns the total number of holds that target the
3236 selected metarecord or its associated copies, call_numbers, and bib records/,
3238 { desc => 'Metarecord ID', type => 'number' },
3240 return => {desc => 'Hold count', type => 'number'}
3244 sub rec_hold_count {
3245 my($self, $conn, $target_id) = @_;
3252 filter => {metarecord => $target_id}
3259 filter => { id => $target_id },
3264 if($self->api_name =~ /mmr/) {
3265 delete $bre_join->{bre}->{filter};
3266 $bre_join->{bre}->{join} = $mmr_join;
3272 fkey => 'call_number',
3278 select => {ahr => [{column => 'id', transform => 'count', alias => 'count'}]},
3282 cancel_time => undef,
3283 fulfillment_time => undef,
3290 select => {acp => ['id']},
3291 from => { acp => $cn_join }
3301 select => {acn => ['id']},
3302 from => {acn => $bre_join}
3310 target => $target_id
3318 if($self->api_name =~ /mmr/) {
3319 $query->{where}->{'+ahr'}->{'-or'}->[2] = {
3324 select => {bre => ['id']},
3325 from => {bre => $mmr_join}
3331 $query->{where}->{'+ahr'}->{'-or'}->[3] = {
3334 target => $target_id
3340 return new_editor()->json_query($query)->[0]->{count};