1 # ---------------------------------------------------------------
2 # Copyright (C) 2005 Georgia Public Library Service
3 # Bill Erickson <highfalutin@gmail.com>
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 # ---------------------------------------------------------------
17 package OpenILS::Application::Circ::Holds;
18 use base qw/OpenILS::Application/;
19 use strict; use warnings;
20 use OpenILS::Application::AppUtils;
23 use OpenSRF::EX qw(:try);
27 use OpenSRF::Utils::Logger qw(:logger);
28 use OpenILS::Utils::CStoreEditor q/:funcs/;
29 use OpenILS::Utils::PermitHold;
30 use OpenSRF::Utils::SettingsClient;
31 use OpenILS::Const qw/:const/;
32 use OpenILS::Application::Circ::Transit;
33 use OpenILS::Application::Actor::Friends;
35 use DateTime::Format::ISO8601;
36 use OpenSRF::Utils qw/:datetime/;
37 use Digest::MD5 qw(md5_hex);
38 use OpenSRF::Utils::Cache;
39 my $apputils = "OpenILS::Application::AppUtils";
42 __PACKAGE__->register_method(
43 method => "test_and_create_hold_batch",
44 api_name => "open-ils.circ.holds.test_and_create.batch",
47 desc => q/This is for batch creating a set of holds where every field is identical except for the targets./,
49 { desc => 'Authentication token', type => 'string' },
50 { desc => 'Hash of named parameters. Same as for open-ils.circ.title_hold.is_possible, though the pertinent target field is automatically populated based on the hold_type and the specified list of targets.', type => 'object'},
51 { desc => 'Array of target ids', type => 'array' }
54 desc => 'Array of hold ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
59 __PACKAGE__->register_method(
60 method => "test_and_create_hold_batch",
61 api_name => "open-ils.circ.holds.test_and_create.batch.override",
64 desc => '@see open-ils.circ.holds.test_and_create.batch',
69 sub test_and_create_hold_batch {
70 my( $self, $conn, $auth, $params, $target_list ) = @_;
72 my $override = 1 if $self->api_name =~ /override/;
74 my $e = new_editor(authtoken=>$auth);
75 return $e->die_event unless $e->checkauth;
76 $$params{'requestor'} = $e->requestor->id;
79 if ($$params{'hold_type'} eq 'T') { $target_field = 'titleid'; }
80 elsif ($$params{'hold_type'} eq 'C') { $target_field = 'copy_id'; }
81 elsif ($$params{'hold_type'} eq 'R') { $target_field = 'copy_id'; }
82 elsif ($$params{'hold_type'} eq 'F') { $target_field = 'copy_id'; }
83 elsif ($$params{'hold_type'} eq 'I') { $target_field = 'issuanceid'; }
84 elsif ($$params{'hold_type'} eq 'V') { $target_field = 'volume_id'; }
85 elsif ($$params{'hold_type'} eq 'M') { $target_field = 'mrid'; }
86 elsif ($$params{'hold_type'} eq 'P') { $target_field = 'partid'; }
87 else { return undef; }
89 foreach (@$target_list) {
90 $$params{$target_field} = $_;
93 ($res) = $self->method_lookup(
94 'open-ils.circ.title_hold.is_possible')->run($auth, $params);
96 if ($override || $res->{'success'} == 1) {
97 my $ahr = construct_hold_request_object($params);
98 my ($res2) = $self->method_lookup(
100 ? 'open-ils.circ.holds.create.override'
101 : 'open-ils.circ.holds.create'
104 'target' => $$params{$target_field},
107 $conn->respond($res2);
110 'target' => $$params{$target_field},
113 $conn->respond($res);
119 sub construct_hold_request_object {
122 my $ahr = Fieldmapper::action::hold_request->new;
125 foreach my $field (keys %{ $params }) {
126 if ($field eq 'depth') { $ahr->selection_depth($$params{$field}); }
127 elsif ($field eq 'patronid') {
128 $ahr->usr($$params{$field}); }
129 elsif ($field eq 'titleid') { $ahr->target($$params{$field}); }
130 elsif ($field eq 'copy_id') { $ahr->target($$params{$field}); }
131 elsif ($field eq 'issuanceid') { $ahr->target($$params{$field}); }
132 elsif ($field eq 'volume_id') { $ahr->target($$params{$field}); }
133 elsif ($field eq 'mrid') { $ahr->target($$params{$field}); }
134 elsif ($field eq 'partid') { $ahr->target($$params{$field}); }
136 $ahr->$field($$params{$field});
142 __PACKAGE__->register_method(
143 method => "create_hold_batch",
144 api_name => "open-ils.circ.holds.create.batch",
147 desc => q/@see open-ils.circ.holds.create.batch/,
149 { desc => 'Authentication token', type => 'string' },
150 { desc => 'Array of hold objects', type => 'array' }
153 desc => 'Array of hold ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
158 __PACKAGE__->register_method(
159 method => "create_hold_batch",
160 api_name => "open-ils.circ.holds.create.override.batch",
163 desc => '@see open-ils.circ.holds.create.batch',
168 sub create_hold_batch {
169 my( $self, $conn, $auth, $hold_list ) = @_;
170 (my $method = $self->api_name) =~ s/\.batch//og;
171 foreach (@$hold_list) {
172 my ($res) = $self->method_lookup($method)->run($auth, $_);
173 $conn->respond($res);
179 __PACKAGE__->register_method(
180 method => "create_hold",
181 api_name => "open-ils.circ.holds.create",
183 desc => "Create a new hold for an item. From a permissions perspective, " .
184 "the login session is used as the 'requestor' of the hold. " .
185 "The hold recipient is determined by the 'usr' setting within the hold object. " .
186 'First we verify the requestor has holds request permissions. ' .
187 'Then we verify that the recipient is allowed to make the given hold. ' .
188 'If not, we see if the requestor has "override" capabilities. If not, ' .
189 'a permission exception is returned. If permissions allow, we cycle ' .
190 'through the set of holds objects and create. ' .
191 'If the recipient does not have permission to place multiple holds ' .
192 'on a single title and said operation is attempted, a permission ' .
193 'exception is returned',
195 { desc => 'Authentication token', type => 'string' },
196 { desc => 'Hold object for hold to be created',
197 type => 'object', class => 'ahr' }
200 desc => 'New ahr ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
205 __PACKAGE__->register_method(
206 method => "create_hold",
207 api_name => "open-ils.circ.holds.create.override",
208 notes => '@see open-ils.circ.holds.create',
210 desc => "If the recipient is not allowed to receive the requested hold, " .
211 "call this method to attempt the override",
213 { desc => 'Authentication token', type => 'string' },
215 desc => 'Hold object for hold to be created',
216 type => 'object', class => 'ahr'
220 desc => 'New hold (ahr) ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
226 my( $self, $conn, $auth, $hold ) = @_;
227 return -1 unless $hold;
228 my $e = new_editor(authtoken=>$auth, xact=>1);
229 return $e->die_event unless $e->checkauth;
231 my $override = 1 if $self->api_name =~ /override/;
235 my $requestor = $e->requestor;
236 my $recipient = $requestor;
238 if( $requestor->id ne $hold->usr ) {
239 # Make sure the requestor is allowed to place holds for
240 # the recipient if they are not the same people
241 $recipient = $e->retrieve_actor_user($hold->usr) or return $e->die_event;
242 $e->allowed('REQUEST_HOLDS', $recipient->home_ou) or return $e->die_event;
245 # If the related org setting tells us to, block if patron privs have expired
246 my $expire_setting = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_BLOCK_HOLD_FOR_EXPIRED_PATRON);
247 if ($expire_setting) {
248 my $expire = DateTime::Format::ISO8601->new->parse_datetime(
249 cleanse_ISO8601($recipient->expire_date));
251 push( @events, OpenILS::Event->new(
252 'PATRON_ACCOUNT_EXPIRED',
253 "payload" => {"fail_part" => "actor.usr.privs_expired"}
254 )) if( CORE::time > $expire->epoch ) ;
257 # Now make sure the recipient is allowed to receive the specified hold
258 my $porg = $recipient->home_ou;
259 my $rid = $e->requestor->id;
260 my $t = $hold->hold_type;
262 # See if a duplicate hold already exists
264 usr => $recipient->id,
266 fulfillment_time => undef,
267 target => $hold->target,
268 cancel_time => undef,
271 $sargs->{holdable_formats} = $hold->holdable_formats if $t eq 'M';
273 my $existing = $e->search_action_hold_request($sargs);
274 push( @events, OpenILS::Event->new('HOLD_EXISTS')) if @$existing;
276 my $checked_out = hold_item_is_checked_out($e, $recipient->id, $hold->hold_type, $hold->target);
277 push( @events, OpenILS::Event->new('HOLD_ITEM_CHECKED_OUT')) if $checked_out;
279 if ( $t eq OILS_HOLD_TYPE_METARECORD ) {
280 return $e->die_event unless $e->allowed('MR_HOLDS', $porg);
281 } elsif ( $t eq OILS_HOLD_TYPE_TITLE ) {
282 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
283 } elsif ( $t eq OILS_HOLD_TYPE_VOLUME ) {
284 return $e->die_event unless $e->allowed('VOLUME_HOLDS', $porg);
285 } elsif ( $t eq OILS_HOLD_TYPE_MONOPART ) {
286 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
287 } elsif ( $t eq OILS_HOLD_TYPE_ISSUANCE ) {
288 return $e->die_event unless $e->allowed('ISSUANCE_HOLDS', $porg);
289 } elsif ( $t eq OILS_HOLD_TYPE_COPY ) {
290 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
291 } elsif ( $t eq OILS_HOLD_TYPE_FORCE ) {
292 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
293 } elsif ( $t eq OILS_HOLD_TYPE_RECALL ) {
294 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
302 for my $evt (@events) {
304 my $name = $evt->{textcode};
305 return $e->die_event unless $e->allowed("$name.override", $porg);
309 # set the configured expire time
310 unless($hold->expire_time) {
311 my $interval = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_HOLD_EXPIRE);
313 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
314 $hold->expire_time($U->epoch2ISO8601($date->epoch));
318 $hold->requestor($e->requestor->id);
319 $hold->request_lib($e->requestor->ws_ou);
320 $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
321 $hold = $e->create_action_hold_request($hold) or return $e->die_event;
325 $conn->respond_complete($hold->id);
328 'open-ils.storage.action.hold_request.copy_targeter',
329 undef, $hold->id ) unless $U->is_true($hold->frozen);
334 # makes sure that a user has permission to place the type of requested hold
335 # returns the Perm exception if not allowed, returns undef if all is well
336 sub _check_holds_perm {
337 my($type, $user_id, $org_id) = @_;
341 $evt = $apputils->check_perms($user_id, $org_id, "MR_HOLDS" );
342 } elsif ($type eq "T") {
343 $evt = $apputils->check_perms($user_id, $org_id, "TITLE_HOLDS" );
344 } elsif($type eq "V") {
345 $evt = $apputils->check_perms($user_id, $org_id, "VOLUME_HOLDS");
346 } elsif($type eq "C") {
347 $evt = $apputils->check_perms($user_id, $org_id, "COPY_HOLDS" );
354 # tests if the given user is allowed to place holds on another's behalf
355 sub _check_request_holds_perm {
358 if (my $evt = $apputils->check_perms(
359 $user_id, $org_id, "REQUEST_HOLDS")) {
364 my $ses_is_req_note = 'The login session is the requestor. If the requestor is different from the user, ' .
365 'then the requestor must have VIEW_HOLD permissions';
367 __PACKAGE__->register_method(
368 method => "retrieve_holds_by_id",
369 api_name => "open-ils.circ.holds.retrieve_by_id",
371 desc => "Retrieve the hold, with hold transits attached, for the specified ID. $ses_is_req_note",
373 { desc => 'Authentication token', type => 'string' },
374 { desc => 'Hold ID', type => 'number' }
377 desc => 'Hold object with transits attached, event on error',
383 sub retrieve_holds_by_id {
384 my($self, $client, $auth, $hold_id) = @_;
385 my $e = new_editor(authtoken=>$auth);
386 $e->checkauth or return $e->event;
387 $e->allowed('VIEW_HOLD') or return $e->event;
389 my $holds = $e->search_action_hold_request(
391 { id => $hold_id , fulfillment_time => undef },
393 order_by => { ahr => "request_time" },
395 flesh_fields => {ahr => ['notes']}
400 flesh_hold_transits($holds);
401 flesh_hold_notices($holds, $e);
406 __PACKAGE__->register_method(
407 method => "retrieve_holds",
408 api_name => "open-ils.circ.holds.retrieve",
410 desc => "Retrieves all the holds, with hold transits attached, for the specified user. $ses_is_req_note",
412 { desc => 'Authentication token', type => 'string' },
413 { desc => 'User ID', type => 'integer' }
416 desc => 'list of holds, event on error',
421 __PACKAGE__->register_method(
422 method => "retrieve_holds",
423 api_name => "open-ils.circ.holds.id_list.retrieve",
426 desc => "Retrieves all the hold IDs, for the specified user. $ses_is_req_note",
428 { desc => 'Authentication token', type => 'string' },
429 { desc => 'User ID', type => 'integer' }
432 desc => 'list of holds, event on error',
437 __PACKAGE__->register_method(
438 method => "retrieve_holds",
439 api_name => "open-ils.circ.holds.canceled.retrieve",
442 desc => "Retrieves all the cancelled holds for the specified user. $ses_is_req_note",
444 { desc => 'Authentication token', type => 'string' },
445 { desc => 'User ID', type => 'integer' }
448 desc => 'list of holds, event on error',
453 __PACKAGE__->register_method(
454 method => "retrieve_holds",
455 api_name => "open-ils.circ.holds.canceled.id_list.retrieve",
458 desc => "Retrieves list of cancelled hold IDs for the specified user. $ses_is_req_note",
460 { desc => 'Authentication token', type => 'string' },
461 { desc => 'User ID', type => 'integer' }
464 desc => 'list of hold IDs, event on error',
471 my ($self, $client, $auth, $user_id) = @_;
473 my $e = new_editor(authtoken=>$auth);
474 return $e->event unless $e->checkauth;
475 $user_id = $e->requestor->id unless defined $user_id;
477 my $notes_filter = {staff => 'f'};
478 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
479 unless($user_id == $e->requestor->id) {
480 if($e->allowed('VIEW_HOLD', $user->home_ou)) {
481 $notes_filter = {staff => 't'}
483 my $allowed = OpenILS::Application::Actor::Friends->friend_perm_allowed(
484 $e, $user_id, $e->requestor->id, 'hold.view');
485 return $e->event unless $allowed;
488 # staff member looking at his/her own holds can see staff and non-staff notes
489 $notes_filter = {} if $e->allowed('VIEW_HOLD', $user->home_ou);
493 select => {ahr => ['id']},
495 where => {usr => $user_id, fulfillment_time => undef}
498 if($self->api_name =~ /canceled/) {
500 # Fetch the canceled holds
501 # order cancelled holds by cancel time, most recent first
503 $holds_query->{order_by} = [{class => 'ahr', field => 'cancel_time', direction => 'desc'}];
506 my $cancel_count = $U->ou_ancestor_setting_value(
507 $e->requestor->ws_ou, 'circ.holds.canceled.display_count', $e);
509 unless($cancel_count) {
510 $cancel_age = $U->ou_ancestor_setting_value(
511 $e->requestor->ws_ou, 'circ.holds.canceled.display_age', $e);
513 # if no settings are defined, default to last 10 cancelled holds
514 $cancel_count = 10 unless $cancel_age;
517 if($cancel_count) { # limit by count
519 $holds_query->{where}->{cancel_time} = {'!=' => undef};
520 $holds_query->{limit} = $cancel_count;
522 } elsif($cancel_age) { # limit by age
524 # find all of the canceled holds that were canceled within the configured time frame
525 my $date = DateTime->now->subtract(seconds => OpenSRF::Utils::interval_to_seconds($cancel_age));
526 $date = $U->epoch2ISO8601($date->epoch);
527 $holds_query->{where}->{cancel_time} = {'>=' => $date};
532 # order non-cancelled holds by ready-for-pickup, then active, followed by suspended
533 $holds_query->{order_by} = {ahr => ['shelf_time', 'frozen', 'request_time']};
534 $holds_query->{where}->{cancel_time} = undef;
537 my $hold_ids = $e->json_query($holds_query);
538 $hold_ids = [ map { $_->{id} } @$hold_ids ];
540 return $hold_ids if $self->api_name =~ /id_list/;
543 for my $hold_id ( @$hold_ids ) {
545 my $hold = $e->retrieve_action_hold_request($hold_id);
546 $hold->notes($e->search_action_hold_request_note({hold => $hold_id, %$notes_filter}));
549 $e->search_action_hold_transit_copy([
551 {order_by => {ahtc => 'source_send_time desc'}, limit => 1}])->[0]
561 __PACKAGE__->register_method(
562 method => 'user_hold_count',
563 api_name => 'open-ils.circ.hold.user.count'
566 sub user_hold_count {
567 my ( $self, $conn, $auth, $userid ) = @_;
568 my $e = new_editor( authtoken => $auth );
569 return $e->event unless $e->checkauth;
570 my $patron = $e->retrieve_actor_user($userid)
572 return $e->event unless $e->allowed( 'VIEW_HOLD', $patron->home_ou );
573 return __user_hold_count( $self, $e, $userid );
576 sub __user_hold_count {
577 my ( $self, $e, $userid ) = @_;
578 my $holds = $e->search_action_hold_request(
581 fulfillment_time => undef,
582 cancel_time => undef,
587 return scalar(@$holds);
591 __PACKAGE__->register_method(
592 method => "retrieve_holds_by_pickup_lib",
593 api_name => "open-ils.circ.holds.retrieve_by_pickup_lib",
595 "Retrieves all the holds, with hold transits attached, for the specified pickup_ou id."
598 __PACKAGE__->register_method(
599 method => "retrieve_holds_by_pickup_lib",
600 api_name => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
601 notes => "Retrieves all the hold ids for the specified pickup_ou id. "
604 sub retrieve_holds_by_pickup_lib {
605 my ($self, $client, $login_session, $ou_id) = @_;
607 #FIXME -- put an appropriate permission check here
608 #my( $user, $target, $evt ) = $apputils->checkses_requestor(
609 # $login_session, $user_id, 'VIEW_HOLD' );
610 #return $evt if $evt;
612 my $holds = $apputils->simplereq(
614 "open-ils.cstore.direct.action.hold_request.search.atomic",
616 pickup_lib => $ou_id ,
617 fulfillment_time => undef,
620 { order_by => { ahr => "request_time" } }
623 if ( ! $self->api_name =~ /id_list/ ) {
624 flesh_hold_transits($holds);
628 return [ map { $_->id } @$holds ];
632 __PACKAGE__->register_method(
633 method => "uncancel_hold",
634 api_name => "open-ils.circ.hold.uncancel"
638 my($self, $client, $auth, $hold_id) = @_;
639 my $e = new_editor(authtoken=>$auth, xact=>1);
640 return $e->die_event unless $e->checkauth;
642 my $hold = $e->retrieve_action_hold_request($hold_id)
643 or return $e->die_event;
644 return $e->die_event unless $e->allowed('CANCEL_HOLDS', $hold->request_lib);
646 if ($hold->fulfillment_time) {
650 unless ($hold->cancel_time) {
655 # if configured to reset the request time, also reset the expire time
656 if($U->ou_ancestor_setting_value(
657 $hold->request_lib, 'circ.holds.uncancel.reset_request_time', $e)) {
659 $hold->request_time('now');
660 my $interval = $U->ou_ancestor_setting_value($hold->request_lib, OILS_SETTING_HOLD_EXPIRE);
662 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
663 $hold->expire_time($U->epoch2ISO8601($date->epoch));
667 $hold->clear_cancel_time;
668 $hold->clear_cancel_cause;
669 $hold->clear_cancel_note;
670 $hold->clear_shelf_time;
671 $hold->clear_current_copy;
672 $hold->clear_capture_time;
673 $hold->clear_prev_check_time;
674 $hold->clear_shelf_expire_time;
676 $e->update_action_hold_request($hold) or return $e->die_event;
679 $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
685 __PACKAGE__->register_method(
686 method => "cancel_hold",
687 api_name => "open-ils.circ.hold.cancel",
689 desc => 'Cancels the specified hold. The login session is the requestor. If the requestor is different from the usr field ' .
690 'on the hold, the requestor must have CANCEL_HOLDS permissions. The hold may be either the hold object or the hold id',
692 {desc => 'Authentication token', type => 'string'},
693 {desc => 'Hold ID', type => 'number'},
694 {desc => 'Cause of Cancellation', type => 'string'},
695 {desc => 'Note', type => 'string'}
698 desc => '1 on success, event on error'
704 my($self, $client, $auth, $holdid, $cause, $note) = @_;
706 my $e = new_editor(authtoken=>$auth, xact=>1);
707 return $e->die_event unless $e->checkauth;
709 my $hold = $e->retrieve_action_hold_request($holdid)
710 or return $e->die_event;
712 if( $e->requestor->id ne $hold->usr ) {
713 return $e->die_event unless $e->allowed('CANCEL_HOLDS');
716 if ($hold->cancel_time) {
721 # If the hold is captured, reset the copy status
722 if( $hold->capture_time and $hold->current_copy ) {
724 my $copy = $e->retrieve_asset_copy($hold->current_copy)
725 or return $e->die_event;
727 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
728 $logger->info("canceling hold $holdid whose item is on the holds shelf");
729 # $logger->info("setting copy to status 'reshelving' on hold cancel");
730 # $copy->status(OILS_COPY_STATUS_RESHELVING);
731 # $copy->editor($e->requestor->id);
732 # $copy->edit_date('now');
733 # $e->update_asset_copy($copy) or return $e->event;
735 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
738 $logger->warn("! canceling hold [$hid] that is in transit");
739 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
742 my $trans = $e->retrieve_action_transit_copy($transid);
743 # Leave the transit alive, but set the copy status to
744 # reshelving so it will be properly reshelved when it gets back home
746 $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
747 $e->update_action_transit_copy($trans) or return $e->die_event;
753 $hold->cancel_time('now');
754 $hold->cancel_cause($cause);
755 $hold->cancel_note($note);
756 $e->update_action_hold_request($hold)
757 or return $e->die_event;
759 delete_hold_copy_maps($self, $e, $hold->id);
763 # re-fetch the hold to pick up the real cancel_time (not "now") for A/T
765 $hold = $e->retrieve_action_hold_request($hold->id) or return $e->die_event;
768 if ($e->requestor->id == $hold->usr) {
769 $U->create_events_for_hook('hold_request.cancel.patron', $hold, $hold->pickup_lib);
771 $U->create_events_for_hook('hold_request.cancel.staff', $hold, $hold->pickup_lib);
777 sub delete_hold_copy_maps {
782 my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
784 $editor->delete_action_hold_copy_map($_)
785 or return $editor->event;
791 my $update_hold_desc = 'The login session is the requestor. ' .
792 'If the requestor is different from the usr field on the hold, ' .
793 'the requestor must have UPDATE_HOLDS permissions. ' .
794 'If supplying a hash of hold data, "id" must be included. ' .
795 'The hash is ignored if a hold object is supplied, ' .
796 'so you should supply only one kind of hold data argument.' ;
798 __PACKAGE__->register_method(
799 method => "update_hold",
800 api_name => "open-ils.circ.hold.update",
802 desc => "Updates the specified hold. $update_hold_desc",
804 {desc => 'Authentication token', type => 'string'},
805 {desc => 'Hold Object', type => 'object'},
806 {desc => 'Hash of values to be applied', type => 'object'}
809 desc => 'Hold ID on success, event on error',
815 __PACKAGE__->register_method(
816 method => "batch_update_hold",
817 api_name => "open-ils.circ.hold.update.batch",
820 desc => "Updates the specified hold(s). $update_hold_desc",
822 {desc => 'Authentication token', type => 'string'},
823 {desc => 'Array of hold obejcts', type => 'array' },
824 {desc => 'Array of hashes of values to be applied', type => 'array' }
827 desc => 'Hold ID per success, event per error',
833 my($self, $client, $auth, $hold, $values) = @_;
834 my $e = new_editor(authtoken=>$auth, xact=>1);
835 return $e->die_event unless $e->checkauth;
836 my $resp = update_hold_impl($self, $e, $hold, $values);
837 if ($U->event_code($resp)) {
841 $e->commit; # FIXME: update_hold_impl already does $e->commit ??
845 sub batch_update_hold {
846 my($self, $client, $auth, $hold_list, $values_list) = @_;
847 my $e = new_editor(authtoken=>$auth);
848 return $e->die_event unless $e->checkauth;
850 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.
852 $values_list ||= []; # FIXME: either move this above $count declaration, or send an event if both lists undef. Probably the latter.
854 # FIXME: Failing over to [] guarantees warnings for "Use of unitialized value" in update_hold_impl call.
855 # FIXME: We should be sure we only call update_hold_impl with hold object OR hash, not both.
857 for my $idx (0..$count-1) {
859 my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
860 $e->xact_commit unless $U->event_code($resp);
861 $client->respond($resp);
865 return undef; # not in the register return type, assuming we should always have at least one list populated
868 sub update_hold_impl {
869 my($self, $e, $hold, $values) = @_;
873 $hold = $e->retrieve_action_hold_request($values->{id})
874 or return $e->die_event;
875 for my $k (keys %$values) {
876 if (defined $values->{$k}) {
877 $hold->$k($values->{$k});
879 my $f = "clear_$k"; $hold->$f();
884 my $orig_hold = $e->retrieve_action_hold_request($hold->id)
885 or return $e->die_event;
887 # don't allow the user to be changed
888 return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
890 if($hold->usr ne $e->requestor->id) {
891 # if the hold is for a different user, make sure the
892 # requestor has the appropriate permissions
893 my $usr = $e->retrieve_actor_user($hold->usr)
894 or return $e->die_event;
895 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
899 # --------------------------------------------------------------
900 # Changing the request time is like playing God
901 # --------------------------------------------------------------
902 if($hold->request_time ne $orig_hold->request_time) {
903 return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
904 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
908 # --------------------------------------------------------------
909 # Code for making sure staff have appropriate permissons for cut_in_line
910 # This, as is, doesn't prevent a user from cutting their own holds in line
912 # --------------------------------------------------------------
913 if($U->is_true($hold->cut_in_line) ne $U->is_true($orig_hold->cut_in_line)) {
914 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
918 # --------------------------------------------------------------
919 # Disallow hold suspencion if the hold is already captured.
920 # --------------------------------------------------------------
921 if ($U->is_true($hold->frozen) and not $U->is_true($orig_hold->frozen)) {
922 $hold_status = _hold_status($e, $hold);
923 if ($hold_status > 2) { # hold is captured
924 $logger->info("bypassing hold freeze on captured hold");
925 return OpenILS::Event->new('HOLD_SUSPEND_AFTER_CAPTURE');
930 # --------------------------------------------------------------
931 # if the hold is on the holds shelf or in transit and the pickup
932 # lib changes we need to create a new transit.
933 # --------------------------------------------------------------
934 if($orig_hold->pickup_lib ne $hold->pickup_lib) {
936 $hold_status = _hold_status($e, $hold) unless $hold_status;
938 if($hold_status == 3) { # in transit
940 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
941 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
943 $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
945 # update the transit to reflect the new pickup location
946 my $transit = $e->search_action_hold_transit_copy(
947 {hold=>$hold->id, dest_recv_time => undef})->[0]
948 or return $e->die_event;
950 $transit->prev_dest($transit->dest); # mark the previous destination on the transit
951 $transit->dest($hold->pickup_lib);
952 $e->update_action_hold_transit_copy($transit) or return $e->die_event;
954 } elsif($hold_status == 4) { # on holds shelf
956 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
957 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
959 $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
961 # create the new transit
962 my $evt = transit_hold($e, $orig_hold, $hold, $e->retrieve_asset_copy($hold->current_copy));
965 # hold is leaving the shelf
966 $hold->clear_shelf_time;
967 $hold->clear_shelf_expire_time;
971 update_hold_if_frozen($self, $e, $hold, $orig_hold);
972 $e->update_action_hold_request($hold) or return $e->die_event;
975 # a change to mint-condition changes the set of potential copies, so retarget the hold;
976 if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
977 _reset_hold($self, $e->requestor, $hold)
984 my($e, $orig_hold, $hold, $copy) = @_;
985 my $src = $orig_hold->pickup_lib;
986 my $dest = $hold->pickup_lib;
988 $logger->info("putting hold into transit on pickup_lib update");
990 my $transit = Fieldmapper::action::hold_transit_copy->new;
991 $transit->hold($hold->id);
992 $transit->source($src);
993 $transit->dest($dest);
994 $transit->target_copy($copy->id);
995 $transit->source_send_time('now');
996 $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
998 $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
999 $copy->editor($e->requestor->id);
1000 $copy->edit_date('now');
1002 $e->create_action_hold_transit_copy($transit) or return $e->die_event;
1003 $e->update_asset_copy($copy) or return $e->die_event;
1007 # if the hold is frozen, this method ensures that the hold is not "targeted",
1008 # that is, it clears the current_copy and prev_check_time to essentiallly
1009 # reset the hold. If it is being activated, it runs the targeter in the background
1010 sub update_hold_if_frozen {
1011 my($self, $e, $hold, $orig_hold) = @_;
1012 return if $hold->capture_time;
1014 if($U->is_true($hold->frozen)) {
1015 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
1016 $hold->clear_current_copy;
1017 $hold->clear_prev_check_time;
1020 if($U->is_true($orig_hold->frozen)) {
1021 $logger->info("Running targeter on activated hold ".$hold->id);
1022 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1027 __PACKAGE__->register_method(
1028 method => "hold_note_CUD",
1029 api_name => "open-ils.circ.hold_request.note.cud",
1031 desc => 'Create, update or delete a hold request note. If the operator (from Auth. token) '
1032 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
1034 { desc => 'Authentication token', type => 'string' },
1035 { desc => 'Hold note object', type => 'object' }
1038 desc => 'Returns the note ID, event on error'
1044 my($self, $conn, $auth, $note) = @_;
1046 my $e = new_editor(authtoken => $auth, xact => 1);
1047 return $e->die_event unless $e->checkauth;
1049 my $hold = $e->retrieve_action_hold_request($note->hold)
1050 or return $e->die_event;
1052 if($hold->usr ne $e->requestor->id) {
1053 my $usr = $e->retrieve_actor_user($hold->usr);
1054 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
1055 $note->staff('t') if $note->isnew;
1059 $e->create_action_hold_request_note($note) or return $e->die_event;
1060 } elsif($note->ischanged) {
1061 $e->update_action_hold_request_note($note) or return $e->die_event;
1062 } elsif($note->isdeleted) {
1063 $e->delete_action_hold_request_note($note) or return $e->die_event;
1071 __PACKAGE__->register_method(
1072 method => "retrieve_hold_status",
1073 api_name => "open-ils.circ.hold.status.retrieve",
1075 desc => 'Calculates the current status of the hold. The requestor must have ' .
1076 'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
1078 { desc => 'Hold ID', type => 'number' }
1081 # type => 'number', # event sometimes
1082 desc => <<'END_OF_DESC'
1083 Returns event on error or:
1084 -1 on error (for now),
1085 1 for 'waiting for copy to become available',
1086 2 for 'waiting for copy capture',
1089 5 for 'hold-shelf-delay'
1096 sub retrieve_hold_status {
1097 my($self, $client, $auth, $hold_id) = @_;
1099 my $e = new_editor(authtoken => $auth);
1100 return $e->event unless $e->checkauth;
1101 my $hold = $e->retrieve_action_hold_request($hold_id)
1102 or return $e->event;
1104 if( $e->requestor->id != $hold->usr ) {
1105 return $e->event unless $e->allowed('VIEW_HOLD');
1108 return _hold_status($e, $hold);
1114 if ($hold->cancel_time) {
1117 return 1 unless $hold->current_copy;
1118 return 2 unless $hold->capture_time;
1120 my $copy = $hold->current_copy;
1121 unless( ref $copy ) {
1122 $copy = $e->retrieve_asset_copy($hold->current_copy)
1123 or return $e->event;
1126 return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
1128 if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
1130 my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
1131 return 4 unless $hs_wait_interval;
1133 # if a hold_shelf_status_delay interval is defined and start_time plus
1134 # the interval is greater than now, consider the hold to be in the virtual
1135 # "on its way to the holds shelf" status. Return 5.
1137 my $transit = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
1138 my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
1139 $start_time = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
1140 my $end_time = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
1142 return 5 if $end_time > DateTime->now;
1151 __PACKAGE__->register_method(
1152 method => "retrieve_hold_queue_stats",
1153 api_name => "open-ils.circ.hold.queue_stats.retrieve",
1155 desc => 'Returns summary data about the state of a hold',
1157 { desc => 'Authentication token', type => 'string'},
1158 { desc => 'Hold ID', type => 'number'},
1161 desc => q/Summary object with keys:
1162 total_holds : total holds in queue
1163 queue_position : current queue position
1164 potential_copies : number of potential copies for this hold
1165 estimated_wait : estimated wait time in days
1166 status : hold status
1167 -1 => error or unexpected state,
1168 1 => 'waiting for copy to become available',
1169 2 => 'waiting for copy capture',
1172 5 => 'hold-shelf-delay'
1179 sub retrieve_hold_queue_stats {
1180 my($self, $conn, $auth, $hold_id) = @_;
1181 my $e = new_editor(authtoken => $auth);
1182 return $e->event unless $e->checkauth;
1183 my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1184 if($e->requestor->id != $hold->usr) {
1185 return $e->event unless $e->allowed('VIEW_HOLD');
1187 return retrieve_hold_queue_status_impl($e, $hold);
1190 sub retrieve_hold_queue_status_impl {
1194 # The holds queue is defined as the distinct set of holds that share at
1195 # least one potential copy with the context hold, plus any holds that
1196 # share the same hold type and target. The latter part exists to
1197 # accomodate holds that currently have no potential copies
1198 my $q_holds = $e->json_query({
1200 # fetch cut_in_line and request_time since they're in the order_by
1201 # and we're asking for distinct values
1202 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1209 'field' => 'target_copy',
1210 'fkey' => 'target_copy'
1219 "field" => "cut_in_line",
1220 "transform" => "coalesce",
1222 "direction" => "desc"
1224 { "class" => "ahr", "field" => "request_time" }
1228 '+ahcm2' => { hold => $hold->id }
1232 if (!@$q_holds) { # none? maybe we don't have a map ...
1233 $q_holds = $e->json_query({
1234 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1239 "field" => "cut_in_line",
1240 "transform" => "coalesce",
1242 "direction" => "desc"
1244 { "class" => "ahr", "field" => "request_time" }
1247 hold_type => $hold->hold_type,
1248 target => $hold->target
1255 for my $h (@$q_holds) {
1256 last if $h->{id} == $hold->id;
1260 my $hold_data = $e->json_query({
1262 acp => [ {column => 'id', transform => 'count', aggregate => 1, alias => 'count'} ],
1263 ccm => [ {column =>'avg_wait_time'} ]
1269 ccm => {type => 'left'}
1274 where => {'+ahcm' => {hold => $hold->id} }
1277 my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1279 my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1280 my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1281 $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1282 $default_wait ||= '0 seconds';
1284 # Estimated wait time is the average wait time across the set
1285 # of potential copies, divided by the number of potential copies
1286 # times the queue position.
1288 my $combined_secs = 0;
1289 my $num_potentials = 0;
1291 for my $wait_data (@$hold_data) {
1292 my $count += $wait_data->{count};
1293 $combined_secs += $count *
1294 OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1295 $num_potentials += $count;
1298 my $estimated_wait = -1;
1300 if($num_potentials) {
1301 my $avg_wait = $combined_secs / $num_potentials;
1302 $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1303 $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1307 total_holds => scalar(@$q_holds),
1308 queue_position => $qpos,
1309 potential_copies => $num_potentials,
1310 status => _hold_status( $e, $hold ),
1311 estimated_wait => int($estimated_wait)
1316 sub fetch_open_hold_by_current_copy {
1319 my $hold = $apputils->simplereq(
1321 'open-ils.cstore.direct.action.hold_request.search.atomic',
1322 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1323 return $hold->[0] if ref($hold);
1327 sub fetch_related_holds {
1330 return $apputils->simplereq(
1332 'open-ils.cstore.direct.action.hold_request.search.atomic',
1333 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1337 __PACKAGE__->register_method(
1338 method => "hold_pull_list",
1339 api_name => "open-ils.circ.hold_pull_list.retrieve",
1341 desc => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1342 'The location is determined by the login session.',
1344 { desc => 'Limit (optional)', type => 'number'},
1345 { desc => 'Offset (optional)', type => 'number'},
1348 desc => 'reference to a list of holds, or event on failure',
1353 __PACKAGE__->register_method(
1354 method => "hold_pull_list",
1355 api_name => "open-ils.circ.hold_pull_list.id_list.retrieve",
1357 desc => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1358 'The location is determined by the login session.',
1360 { desc => 'Limit (optional)', type => 'number'},
1361 { desc => 'Offset (optional)', type => 'number'},
1364 desc => 'reference to a list of holds, or event on failure',
1369 __PACKAGE__->register_method(
1370 method => "hold_pull_list",
1371 api_name => "open-ils.circ.hold_pull_list.retrieve.count",
1373 desc => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1374 'The location is determined by the login session.',
1376 { desc => 'Limit (optional)', type => 'number'},
1377 { desc => 'Offset (optional)', type => 'number'},
1380 desc => 'Holds count (integer), or event on failure',
1387 sub hold_pull_list {
1388 my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1389 my( $reqr, $evt ) = $U->checkses($authtoken);
1390 return $evt if $evt;
1392 my $org = $reqr->ws_ou || $reqr->home_ou;
1393 # the perm locaiton shouldn't really matter here since holds
1394 # will exist all over and VIEW_HOLDS should be universal
1395 $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1396 return $evt if $evt;
1398 if($self->api_name =~ /count/) {
1400 my $count = $U->storagereq(
1401 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1402 $org, $limit, $offset );
1404 $logger->info("Grabbing pull list for org unit $org with $count items");
1407 } elsif( $self->api_name =~ /id_list/ ) {
1408 return $U->storagereq(
1409 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1410 $org, $limit, $offset );
1413 return $U->storagereq(
1414 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1415 $org, $limit, $offset );
1419 __PACKAGE__->register_method(
1420 method => "print_hold_pull_list",
1421 api_name => "open-ils.circ.hold_pull_list.print",
1423 desc => 'Returns an HTML-formatted holds pull list',
1425 { desc => 'Authtoken', type => 'string'},
1426 { desc => 'Org unit ID. Optional, defaults to workstation org unit', type => 'number'},
1429 desc => 'HTML string',
1435 sub print_hold_pull_list {
1436 my($self, $client, $auth, $org_id) = @_;
1438 my $e = new_editor(authtoken=>$auth);
1439 return $e->event unless $e->checkauth;
1441 $org_id = (defined $org_id) ? $org_id : $e->requestor->ws_ou;
1442 return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1444 my $hold_ids = $U->storagereq(
1445 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1448 return undef unless @$hold_ids;
1450 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1452 # Holds will /NOT/ be in order after this ...
1453 my $holds = $e->search_action_hold_request({id => $hold_ids}, {substream => 1});
1454 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1456 # ... so we must resort.
1457 my $hold_map = +{map { $_->id => $_ } @$holds};
1458 my $sorted_holds = [];
1459 push @$sorted_holds, $hold_map->{$_} foreach @$hold_ids;
1461 return $U->fire_object_event(
1462 undef, "ahr.format.pull_list", $sorted_holds,
1463 $org_id, undef, undef, $client
1468 __PACKAGE__->register_method(
1469 method => "print_hold_pull_list_stream",
1471 api_name => "open-ils.circ.hold_pull_list.print.stream",
1473 desc => 'Returns a stream of fleshed holds',
1475 { desc => 'Authtoken', type => 'string'},
1476 { desc => 'Hash of optional param: Org unit ID (defaults to workstation org unit), limit, offset, sort (array of: acplo.position, prefix, call_number, suffix, request_time)',
1481 desc => 'A stream of fleshed holds',
1487 sub print_hold_pull_list_stream {
1488 my($self, $client, $auth, $params) = @_;
1490 my $e = new_editor(authtoken=>$auth);
1491 return $e->die_event unless $e->checkauth;
1493 delete($$params{org_id}) unless (int($$params{org_id}));
1494 delete($$params{limit}) unless (int($$params{limit}));
1495 delete($$params{offset}) unless (int($$params{offset}));
1496 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1497 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1498 $$params{chunk_size} ||= 10;
1500 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1501 return $e->die_event unless $e->allowed('VIEW_HOLD', $$params{org_id });
1504 if ($$params{sort} && @{ $$params{sort} }) {
1505 for my $s (@{ $$params{sort} }) {
1506 if ($s eq 'acplo.position') {
1508 "class" => "acplo", "field" => "position",
1509 "transform" => "coalesce", "params" => [999]
1511 } elsif ($s eq 'prefix') {
1512 push @$sort, {"class" => "acnp", "field" => "label_sortkey"};
1513 } elsif ($s eq 'call_number') {
1514 push @$sort, {"class" => "acn", "field" => "label_sortkey"};
1515 } elsif ($s eq 'suffix') {
1516 push @$sort, {"class" => "acns", "field" => "label_sortkey"};
1517 } elsif ($s eq 'request_time') {
1518 push @$sort, {"class" => "ahr", "field" => "request_time"};
1522 push @$sort, {"class" => "ahr", "field" => "request_time"};
1525 my $holds_ids = $e->json_query(
1527 "select" => {"ahr" => ["id"]},
1532 "fkey" => "current_copy",
1534 "circ_lib" => $$params{org_id}, "status" => [0,7]
1539 "fkey" => "call_number",
1553 "fkey" => "circ_lib",
1556 "location" => {"=" => {"+acp" => "location"}}
1565 "capture_time" => undef,
1566 "cancel_time" => undef,
1568 {"expire_time" => undef },
1569 {"expire_time" => {">" => "now"}}
1573 (@$sort ? (order_by => $sort) : ()),
1574 ($$params{limit} ? (limit => $$params{limit}) : ()),
1575 ($$params{offset} ? (offset => $$params{offset}) : ())
1576 }, {"substream" => 1}
1577 ) or return $e->die_event;
1579 $logger->info("about to stream back " . scalar(@$holds_ids) . " holds");
1582 for my $hid (@$holds_ids) {
1583 push @chunk, $e->retrieve_action_hold_request([
1587 "ahr" => ["usr", "current_copy"],
1589 "acp" => ["location", "call_number", "parts"],
1590 "acn" => ["record","prefix","suffix"]
1595 if (@chunk >= $$params{chunk_size}) {
1596 $client->respond( \@chunk );
1600 $client->respond_complete( \@chunk ) if (@chunk);
1607 __PACKAGE__->register_method(
1608 method => 'fetch_hold_notify',
1609 api_name => 'open-ils.circ.hold_notification.retrieve_by_hold',
1612 Returns a list of hold notification objects based on hold id.
1613 @param authtoken The loggin session key
1614 @param holdid The id of the hold whose notifications we want to retrieve
1615 @return An array of hold notification objects, event on error.
1619 sub fetch_hold_notify {
1620 my( $self, $conn, $authtoken, $holdid ) = @_;
1621 my( $requestor, $evt ) = $U->checkses($authtoken);
1622 return $evt if $evt;
1623 my ($hold, $patron);
1624 ($hold, $evt) = $U->fetch_hold($holdid);
1625 return $evt if $evt;
1626 ($patron, $evt) = $U->fetch_user($hold->usr);
1627 return $evt if $evt;
1629 $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1630 return $evt if $evt;
1632 $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1633 return $U->cstorereq(
1634 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1638 __PACKAGE__->register_method(
1639 method => 'create_hold_notify',
1640 api_name => 'open-ils.circ.hold_notification.create',
1642 Creates a new hold notification object
1643 @param authtoken The login session key
1644 @param notification The hold notification object to create
1645 @return ID of the new object on success, Event on error
1649 sub create_hold_notify {
1650 my( $self, $conn, $auth, $note ) = @_;
1651 my $e = new_editor(authtoken=>$auth, xact=>1);
1652 return $e->die_event unless $e->checkauth;
1654 my $hold = $e->retrieve_action_hold_request($note->hold)
1655 or return $e->die_event;
1656 my $patron = $e->retrieve_actor_user($hold->usr)
1657 or return $e->die_event;
1659 return $e->die_event unless
1660 $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1662 $note->notify_staff($e->requestor->id);
1663 $e->create_action_hold_notification($note) or return $e->die_event;
1668 __PACKAGE__->register_method(
1669 method => 'create_hold_note',
1670 api_name => 'open-ils.circ.hold_note.create',
1672 Creates a new hold request note object
1673 @param authtoken The login session key
1674 @param note The hold note object to create
1675 @return ID of the new object on success, Event on error
1679 sub create_hold_note {
1680 my( $self, $conn, $auth, $note ) = @_;
1681 my $e = new_editor(authtoken=>$auth, xact=>1);
1682 return $e->die_event unless $e->checkauth;
1684 my $hold = $e->retrieve_action_hold_request($note->hold)
1685 or return $e->die_event;
1686 my $patron = $e->retrieve_actor_user($hold->usr)
1687 or return $e->die_event;
1689 return $e->die_event unless
1690 $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn. Probably want something more specific
1692 $e->create_action_hold_request_note($note) or return $e->die_event;
1697 __PACKAGE__->register_method(
1698 method => 'reset_hold',
1699 api_name => 'open-ils.circ.hold.reset',
1701 Un-captures and un-targets a hold, essentially returning
1702 it to the state it was in directly after it was placed,
1703 then attempts to re-target the hold
1704 @param authtoken The login session key
1705 @param holdid The id of the hold
1711 my( $self, $conn, $auth, $holdid ) = @_;
1713 my ($hold, $evt) = $U->fetch_hold($holdid);
1714 return $evt if $evt;
1715 ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1716 return $evt if $evt;
1717 $evt = _reset_hold($self, $reqr, $hold);
1718 return $evt if $evt;
1723 __PACKAGE__->register_method(
1724 method => 'reset_hold_batch',
1725 api_name => 'open-ils.circ.hold.reset.batch'
1728 sub reset_hold_batch {
1729 my($self, $conn, $auth, $hold_ids) = @_;
1731 my $e = new_editor(authtoken => $auth);
1732 return $e->event unless $e->checkauth;
1734 for my $hold_id ($hold_ids) {
1736 my $hold = $e->retrieve_action_hold_request(
1737 [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}])
1738 or return $e->event;
1740 next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1741 _reset_hold($self, $e->requestor, $hold);
1749 my ($self, $reqr, $hold) = @_;
1751 my $e = new_editor(xact =>1, requestor => $reqr);
1753 $logger->info("reseting hold ".$hold->id);
1755 my $hid = $hold->id;
1757 if( $hold->capture_time and $hold->current_copy ) {
1759 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1760 or return $e->die_event;
1762 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1763 $logger->info("setting copy to status 'reshelving' on hold retarget");
1764 $copy->status(OILS_COPY_STATUS_RESHELVING);
1765 $copy->editor($e->requestor->id);
1766 $copy->edit_date('now');
1767 $e->update_asset_copy($copy) or return $e->die_event;
1769 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1771 # We don't want the copy to remain "in transit"
1772 $copy->status(OILS_COPY_STATUS_RESHELVING);
1773 $logger->warn("! reseting hold [$hid] that is in transit");
1774 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1777 my $trans = $e->retrieve_action_transit_copy($transid);
1779 $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1780 my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1);
1781 $logger->info("Transit abort completed with result $evt");
1782 unless ("$evt" eq 1) {
1791 $hold->clear_capture_time;
1792 $hold->clear_current_copy;
1793 $hold->clear_shelf_time;
1794 $hold->clear_shelf_expire_time;
1796 $e->update_action_hold_request($hold) or return $e->die_event;
1800 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1806 __PACKAGE__->register_method(
1807 method => 'fetch_open_title_holds',
1808 api_name => 'open-ils.circ.open_holds.retrieve',
1810 Returns a list ids of un-fulfilled holds for a given title id
1811 @param authtoken The login session key
1812 @param id the id of the item whose holds we want to retrieve
1813 @param type The hold type - M, T, I, V, C, F, R
1817 sub fetch_open_title_holds {
1818 my( $self, $conn, $auth, $id, $type, $org ) = @_;
1819 my $e = new_editor( authtoken => $auth );
1820 return $e->event unless $e->checkauth;
1823 $org ||= $e->requestor->ws_ou;
1825 # return $e->search_action_hold_request(
1826 # { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1828 # XXX make me return IDs in the future ^--
1829 my $holds = $e->search_action_hold_request(
1832 cancel_time => undef,
1834 fulfillment_time => undef
1838 flesh_hold_transits($holds);
1843 sub flesh_hold_transits {
1845 for my $hold ( @$holds ) {
1847 $apputils->simplereq(
1849 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1850 { hold => $hold->id },
1851 { order_by => { ahtc => 'id desc' }, limit => 1 }
1857 sub flesh_hold_notices {
1858 my( $holds, $e ) = @_;
1859 $e ||= new_editor();
1861 for my $hold (@$holds) {
1862 my $notices = $e->search_action_hold_notification(
1864 { hold => $hold->id },
1865 { order_by => { anh => 'notify_time desc' } },
1870 $hold->notify_count(scalar(@$notices));
1872 my $n = $e->retrieve_action_hold_notification($$notices[0])
1873 or return $e->event;
1874 $hold->notify_time($n->notify_time);
1880 __PACKAGE__->register_method(
1881 method => 'fetch_captured_holds',
1882 api_name => 'open-ils.circ.captured_holds.on_shelf.retrieve',
1886 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
1887 @param authtoken The login session key
1888 @param org The org id of the location in question
1892 __PACKAGE__->register_method(
1893 method => 'fetch_captured_holds',
1894 api_name => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
1898 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
1899 @param authtoken The login session key
1900 @param org The org id of the location in question
1904 __PACKAGE__->register_method(
1905 method => 'fetch_captured_holds',
1906 api_name => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
1910 Returns list ids of shelf-expired un-fulfilled holds for a given title id
1911 @param authtoken The login session key
1912 @param org The org id of the location in question
1917 sub fetch_captured_holds {
1918 my( $self, $conn, $auth, $org ) = @_;
1920 my $e = new_editor(authtoken => $auth);
1921 return $e->die_event unless $e->checkauth;
1922 return $e->die_event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
1924 $org ||= $e->requestor->ws_ou;
1927 select => { alhr => ['id'] },
1932 fkey => 'current_copy'
1937 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
1939 capture_time => { "!=" => undef },
1940 current_copy => { "!=" => undef },
1941 fulfillment_time => undef,
1943 # cancel_time => undef,
1947 if($self->api_name =~ /expired/) {
1948 # $query->{'where'}->{'+ahr'}->{'shelf_expire_time'} = {'<' => 'now'};
1949 $query->{'where'}->{'+alhr'}->{'shelf_time'} = {'!=' => undef};
1950 $query->{'where'}->{'+alhr'}->{'-or'} = {
1951 shelf_expire_time => { '<' => 'now'},
1952 cancel_time => { '!=' => undef },
1955 my $hold_ids = $e->json_query( $query );
1957 for my $hold_id (@$hold_ids) {
1958 if($self->api_name =~ /id_list/) {
1959 $conn->respond($hold_id->{id});
1963 $e->retrieve_action_hold_request([
1967 flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
1968 order_by => {anh => 'notify_time desc'}
1978 __PACKAGE__->register_method(
1979 method => "print_expired_holds_stream",
1980 api_name => "open-ils.circ.captured_holds.expired.print.stream",
1984 sub print_expired_holds_stream {
1985 my ($self, $client, $auth, $params) = @_;
1987 # No need to check specific permissions: we're going to call another method
1988 # that will do that.
1989 my $e = new_editor("authtoken" => $auth);
1990 return $e->die_event unless $e->checkauth;
1992 delete($$params{org_id}) unless (int($$params{org_id}));
1993 delete($$params{limit}) unless (int($$params{limit}));
1994 delete($$params{offset}) unless (int($$params{offset}));
1995 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1996 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1997 $$params{chunk_size} ||= 10;
1999 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
2001 my @hold_ids = $self->method_lookup(
2002 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
2003 )->run($auth, $params->{"org_id"});
2008 } elsif (defined $U->event_code($hold_ids[0])) {
2010 return $hold_ids[0];
2013 $logger->info("about to stream back up to " . scalar(@hold_ids) . " expired holds");
2016 my @hid_chunk = splice @hold_ids, 0, $params->{"chunk_size"};
2018 my $result_chunk = $e->json_query({
2020 "acp" => ["barcode"],
2022 first_given_name second_given_name family_name alias
2031 "field" => "id", "fkey" => "current_copy",
2034 "field" => "id", "fkey" => "call_number",
2037 "field" => "id", "fkey" => "record"
2041 "acpl" => {"field" => "id", "fkey" => "location"}
2044 "au" => {"field" => "id", "fkey" => "usr"}
2047 "where" => {"+ahr" => {"id" => \@hid_chunk}}
2048 }) or return $e->die_event;
2049 $client->respond($result_chunk);
2056 __PACKAGE__->register_method(
2057 method => "check_title_hold_batch",
2058 api_name => "open-ils.circ.title_hold.is_possible.batch",
2061 desc => '@see open-ils.circ.title_hold.is_possible.batch',
2063 { desc => 'Authentication token', type => 'string'},
2064 { desc => 'Array of Hash of named parameters', type => 'array'},
2067 desc => 'Array of response objects',
2073 sub check_title_hold_batch {
2074 my($self, $client, $authtoken, $param_list) = @_;
2075 foreach (@$param_list) {
2076 my ($res) = $self->method_lookup('open-ils.circ.title_hold.is_possible')->run($authtoken, $_);
2077 $client->respond($res);
2083 __PACKAGE__->register_method(
2084 method => "check_title_hold",
2085 api_name => "open-ils.circ.title_hold.is_possible",
2087 desc => 'Determines if a hold were to be placed by a given user, ' .
2088 'whether or not said hold would have any potential copies to fulfill it.' .
2089 'The named paramaters of the second argument include: ' .
2090 'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
2091 'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' ,
2093 { desc => 'Authentication token', type => 'string'},
2094 { desc => 'Hash of named parameters', type => 'object'},
2097 desc => 'List of new message IDs (empty if none)',
2103 =head3 check_title_hold (token, hash)
2105 The named fields in the hash are:
2107 patronid - ID of the hold recipient (required)
2108 depth - hold range depth (default 0)
2109 pickup_lib - destination for hold, fallback value for selection_ou
2110 selection_ou - ID of org_unit establishing hard and soft hold boundary settings
2111 issuanceid - ID of the issuance to be held, required for Issuance level hold
2112 partid - ID of the monograph part to be held, required for monograph part level hold
2113 titleid - ID (BRN) of the title to be held, required for Title level hold
2114 volume_id - required for Volume level hold
2115 copy_id - required for Copy level hold
2116 mrid - required for Meta-record level hold
2117 hold_type - T, C (or R or F), I, V or M for Title, Copy, Issuance, Volume or Meta-record (default "T")
2119 All key/value pairs are passed on to do_possibility_checks.
2123 # FIXME: better params checking. what other params are required, if any?
2124 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
2125 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still
2126 # used in conditionals, where it may be undefined, causing a warning.
2127 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
2129 sub check_title_hold {
2130 my( $self, $client, $authtoken, $params ) = @_;
2131 my $e = new_editor(authtoken=>$authtoken);
2132 return $e->event unless $e->checkauth;
2134 my %params = %$params;
2135 my $depth = $params{depth} || 0;
2136 my $selection_ou = $params{selection_ou} || $params{pickup_lib};
2138 my $patron = $e->retrieve_actor_user($params{patronid})
2139 or return $e->event;
2141 if( $e->requestor->id ne $patron->id ) {
2142 return $e->event unless
2143 $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
2146 return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
2148 my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
2149 or return $e->event;
2151 my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
2152 my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
2155 my $return_depth = $hard_boundary; # default depth to return on success
2156 if(defined $soft_boundary and $depth < $soft_boundary) {
2157 # work up the tree and as soon as we find a potential copy, use that depth
2158 # also, make sure we don't go past the hard boundary if it exists
2160 # our min boundary is the greater of user-specified boundary or hard boundary
2161 my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?
2162 $hard_boundary : $depth;
2164 my $depth = $soft_boundary;
2165 while($depth >= $min_depth) {
2166 $logger->info("performing hold possibility check with soft boundary $depth");
2167 @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
2169 $return_depth = $depth;
2174 } elsif(defined $hard_boundary and $depth < $hard_boundary) {
2175 # there is no soft boundary, enforce the hard boundary if it exists
2176 $logger->info("performing hold possibility check with hard boundary $hard_boundary");
2177 @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
2179 # no boundaries defined, fall back to user specifed boundary or no boundary
2180 $logger->info("performing hold possibility check with no boundary");
2181 @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
2187 "depth" => $return_depth,
2188 "local_avail" => $status[1]
2190 } elsif ($status[2]) {
2191 my $n = scalar @{$status[2]};
2192 return {"success" => 0, "last_event" => $status[2]->[$n - 1]};
2194 return {"success" => 0};
2200 sub do_possibility_checks {
2201 my($e, $patron, $request_lib, $depth, %params) = @_;
2203 my $issuanceid = $params{issuanceid} || "";
2204 my $partid = $params{partid} || "";
2205 my $titleid = $params{titleid} || "";
2206 my $volid = $params{volume_id};
2207 my $copyid = $params{copy_id};
2208 my $mrid = $params{mrid} || "";
2209 my $pickup_lib = $params{pickup_lib};
2210 my $hold_type = $params{hold_type} || 'T';
2211 my $selection_ou = $params{selection_ou} || $pickup_lib;
2212 my $holdable_formats = $params{holdable_formats};
2219 if( $hold_type eq OILS_HOLD_TYPE_FORCE || $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_COPY ) {
2221 return $e->event unless $copy = $e->retrieve_asset_copy($copyid);
2222 return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
2223 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2225 return verify_copy_for_hold(
2226 $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib
2229 } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2231 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
2232 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2234 return _check_volume_hold_is_possible(
2235 $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2238 } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
2240 return _check_title_hold_is_possible(
2241 $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2244 } elsif( $hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2246 return _check_issuance_hold_is_possible(
2247 $issuanceid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2250 } elsif( $hold_type eq OILS_HOLD_TYPE_MONOPART ) {
2252 return _check_monopart_hold_is_possible(
2253 $partid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2256 } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2258 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
2259 my @recs = map { $_->source } @$maps;
2261 for my $rec (@recs) {
2262 @status = _check_title_hold_is_possible(
2263 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $holdable_formats
2269 # else { Unrecognized hold_type ! } # FIXME: return error? or 0?
2273 sub create_ranged_org_filter {
2274 my($e, $selection_ou, $depth) = @_;
2276 # find the orgs from which this hold may be fulfilled,
2277 # based on the selection_ou and depth
2279 my $top_org = $e->search_actor_org_unit([
2280 {parent_ou => undef},
2281 {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
2284 return () if $depth == $top_org->ou_type->depth;
2286 my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
2287 %org_filter = (circ_lib => []);
2288 push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
2290 $logger->info("hold org filter at depth $depth and selection_ou ".
2291 "$selection_ou created list of @{$org_filter{circ_lib}}");
2297 sub _check_title_hold_is_possible {
2298 my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $holdable_formats ) = @_;
2300 my ($types, $formats, $lang);
2301 if (defined($holdable_formats)) {
2302 ($types, $formats, $lang) = split '-', $holdable_formats;
2305 my $e = new_editor();
2306 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2308 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2309 my $copies = $e->json_query(
2311 select => { acp => ['id', 'circ_lib'] },
2316 fkey => 'call_number',
2320 filter => { id => $titleid },
2328 ( $types ? (item_type => [split '', $types]) : () ),
2329 ( $formats ? (item_form => [split '', $formats]) : () ),
2330 ( $lang ? (item_lang => $lang) : () )
2335 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2336 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' },
2337 acpm => { field => 'target_copy', type => 'left' } # ignore part-linked copies
2341 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter },
2342 '+acpm' => { target_copy => undef } # ignore part-linked copies
2347 $logger->info("title possible found ".scalar(@$copies)." potential copies");
2351 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2352 "payload" => {"fail_part" => "no_ultimate_items"}
2357 # -----------------------------------------------------------------------
2358 # sort the copies into buckets based on their circ_lib proximity to
2359 # the patron's home_ou.
2360 # -----------------------------------------------------------------------
2362 my $home_org = $patron->home_ou;
2363 my $req_org = $request_lib->id;
2365 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2367 $prox_cache{$home_org} =
2368 $e->search_actor_org_unit_proximity({from_org => $home_org})
2369 unless $prox_cache{$home_org};
2370 my $home_prox = $prox_cache{$home_org};
2373 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2374 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2376 my @keys = sort { $a <=> $b } keys %buckets;
2379 if( $home_org ne $req_org ) {
2380 # -----------------------------------------------------------------------
2381 # shove the copies close to the request_lib into the primary buckets
2382 # directly before the farthest away copies. That way, they are not
2383 # given priority, but they are checked before the farthest copies.
2384 # -----------------------------------------------------------------------
2385 $prox_cache{$req_org} =
2386 $e->search_actor_org_unit_proximity({from_org => $req_org})
2387 unless $prox_cache{$req_org};
2388 my $req_prox = $prox_cache{$req_org};
2391 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2392 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2394 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2395 my $new_key = $highest_key - 0.5; # right before the farthest prox
2396 my @keys2 = sort { $a <=> $b } keys %buckets2;
2397 for my $key (@keys2) {
2398 last if $key >= $highest_key;
2399 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2403 @keys = sort { $a <=> $b } keys %buckets;
2408 OUTER: for my $key (@keys) {
2409 my @cps = @{$buckets{$key}};
2411 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2413 for my $copyid (@cps) {
2415 next if $seen{$copyid};
2416 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2417 my $copy = $e->retrieve_asset_copy($copyid);
2418 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2420 unless($title) { # grab the title if we don't already have it
2421 my $vol = $e->retrieve_asset_call_number(
2422 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2423 $title = $vol->record;
2426 @status = verify_copy_for_hold(
2427 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2429 last OUTER if $status[0];
2436 sub _check_issuance_hold_is_possible {
2437 my( $issuanceid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2439 my $e = new_editor();
2440 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2442 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2443 my $copies = $e->json_query(
2445 select => { acp => ['id', 'circ_lib'] },
2451 filter => { issuance => $issuanceid }
2453 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2454 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2458 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2464 $logger->info("issuance possible found ".scalar(@$copies)." potential copies");
2468 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2469 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2474 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2475 "payload" => {"fail_part" => "no_ultimate_items"}
2483 # -----------------------------------------------------------------------
2484 # sort the copies into buckets based on their circ_lib proximity to
2485 # the patron's home_ou.
2486 # -----------------------------------------------------------------------
2488 my $home_org = $patron->home_ou;
2489 my $req_org = $request_lib->id;
2491 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2493 $prox_cache{$home_org} =
2494 $e->search_actor_org_unit_proximity({from_org => $home_org})
2495 unless $prox_cache{$home_org};
2496 my $home_prox = $prox_cache{$home_org};
2499 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2500 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2502 my @keys = sort { $a <=> $b } keys %buckets;
2505 if( $home_org ne $req_org ) {
2506 # -----------------------------------------------------------------------
2507 # shove the copies close to the request_lib into the primary buckets
2508 # directly before the farthest away copies. That way, they are not
2509 # given priority, but they are checked before the farthest copies.
2510 # -----------------------------------------------------------------------
2511 $prox_cache{$req_org} =
2512 $e->search_actor_org_unit_proximity({from_org => $req_org})
2513 unless $prox_cache{$req_org};
2514 my $req_prox = $prox_cache{$req_org};
2517 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2518 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2520 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2521 my $new_key = $highest_key - 0.5; # right before the farthest prox
2522 my @keys2 = sort { $a <=> $b } keys %buckets2;
2523 for my $key (@keys2) {
2524 last if $key >= $highest_key;
2525 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2529 @keys = sort { $a <=> $b } keys %buckets;
2534 OUTER: for my $key (@keys) {
2535 my @cps = @{$buckets{$key}};
2537 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2539 for my $copyid (@cps) {
2541 next if $seen{$copyid};
2542 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2543 my $copy = $e->retrieve_asset_copy($copyid);
2544 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2546 unless($title) { # grab the title if we don't already have it
2547 my $vol = $e->retrieve_asset_call_number(
2548 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2549 $title = $vol->record;
2552 @status = verify_copy_for_hold(
2553 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2555 last OUTER if $status[0];
2560 if (!defined($empty_ok)) {
2561 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2562 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2565 return (1,0) if ($empty_ok);
2570 sub _check_monopart_hold_is_possible {
2571 my( $partid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2573 my $e = new_editor();
2574 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2576 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2577 my $copies = $e->json_query(
2579 select => { acp => ['id', 'circ_lib'] },
2583 field => 'target_copy',
2585 filter => { part => $partid }
2587 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2588 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2592 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2598 $logger->info("monopart possible found ".scalar(@$copies)." potential copies");
2602 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2603 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2608 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2609 "payload" => {"fail_part" => "no_ultimate_items"}
2617 # -----------------------------------------------------------------------
2618 # sort the copies into buckets based on their circ_lib proximity to
2619 # the patron's home_ou.
2620 # -----------------------------------------------------------------------
2622 my $home_org = $patron->home_ou;
2623 my $req_org = $request_lib->id;
2625 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2627 $prox_cache{$home_org} =
2628 $e->search_actor_org_unit_proximity({from_org => $home_org})
2629 unless $prox_cache{$home_org};
2630 my $home_prox = $prox_cache{$home_org};
2633 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2634 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2636 my @keys = sort { $a <=> $b } keys %buckets;
2639 if( $home_org ne $req_org ) {
2640 # -----------------------------------------------------------------------
2641 # shove the copies close to the request_lib into the primary buckets
2642 # directly before the farthest away copies. That way, they are not
2643 # given priority, but they are checked before the farthest copies.
2644 # -----------------------------------------------------------------------
2645 $prox_cache{$req_org} =
2646 $e->search_actor_org_unit_proximity({from_org => $req_org})
2647 unless $prox_cache{$req_org};
2648 my $req_prox = $prox_cache{$req_org};
2651 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2652 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2654 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2655 my $new_key = $highest_key - 0.5; # right before the farthest prox
2656 my @keys2 = sort { $a <=> $b } keys %buckets2;
2657 for my $key (@keys2) {
2658 last if $key >= $highest_key;
2659 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2663 @keys = sort { $a <=> $b } keys %buckets;
2668 OUTER: for my $key (@keys) {
2669 my @cps = @{$buckets{$key}};
2671 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2673 for my $copyid (@cps) {
2675 next if $seen{$copyid};
2676 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2677 my $copy = $e->retrieve_asset_copy($copyid);
2678 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2680 unless($title) { # grab the title if we don't already have it
2681 my $vol = $e->retrieve_asset_call_number(
2682 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2683 $title = $vol->record;
2686 @status = verify_copy_for_hold(
2687 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2689 last OUTER if $status[0];
2694 if (!defined($empty_ok)) {
2695 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2696 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2699 return (1,0) if ($empty_ok);
2705 sub _check_volume_hold_is_possible {
2706 my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2707 my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
2708 my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
2709 $logger->info("checking possibility of volume hold for volume ".$vol->id);
2711 my $filter_copies = [];
2712 for my $copy (@$copies) {
2713 # ignore part-mapped copies for regular volume level holds
2714 push(@$filter_copies, $copy) unless
2715 new_editor->search_asset_copy_part_map({target_copy => $copy->id})->[0];
2717 $copies = $filter_copies;
2722 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2723 "payload" => {"fail_part" => "no_ultimate_items"}
2729 for my $copy ( @$copies ) {
2730 @status = verify_copy_for_hold(
2731 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
2739 sub verify_copy_for_hold {
2740 my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib ) = @_;
2741 $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
2742 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2743 { patron => $patron,
2744 requestor => $requestor,
2747 title_descriptor => $title->fixed_fields, # this is fleshed into the title object
2748 pickup_lib => $pickup_lib,
2749 request_lib => $request_lib,
2751 show_event_list => 1
2756 (not scalar @$permitted), # true if permitted is an empty arrayref
2757 ( # XXX This test is of very dubious value; someone should figure
2758 # out what if anything is checking this value
2759 ($copy->circ_lib == $pickup_lib) and
2760 ($copy->status == OILS_COPY_STATUS_AVAILABLE)
2768 sub find_nearest_permitted_hold {
2771 my $editor = shift; # CStoreEditor object
2772 my $copy = shift; # copy to target
2773 my $user = shift; # staff
2774 my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
2776 my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
2778 my $bc = $copy->barcode;
2780 # find any existing holds that already target this copy
2781 my $old_holds = $editor->search_action_hold_request(
2782 { current_copy => $copy->id,
2783 cancel_time => undef,
2784 capture_time => undef
2788 # hold->type "R" means we need this copy
2789 for my $h (@$old_holds) { return ($h) if $h->hold_type eq 'R'; }
2792 my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
2794 $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
2795 " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
2797 my $fifo = $U->ou_ancestor_setting_value($user->ws_ou, 'circ.holds_fifo');
2799 # search for what should be the best holds for this copy to fulfill
2800 my $best_holds = $U->storagereq(
2801 "open-ils.storage.action.hold_request.nearest_hold.atomic",
2802 $user->ws_ou, $copy->id, 10, $hold_stall_interval, $fifo );
2804 unless(@$best_holds) {
2806 if( my $hold = $$old_holds[0] ) {
2807 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2811 $logger->info("circulator: no suitable holds found for copy $bc");
2812 return (undef, $evt);
2818 # for each potential hold, we have to run the permit script
2819 # to make sure the hold is actually permitted.
2822 for my $holdid (@$best_holds) {
2823 next unless $holdid;
2824 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
2826 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
2827 my $reqr = $reqr_cache{$hold->requestor} || $editor->retrieve_actor_user($hold->requestor);
2828 my $rlib = $org_cache{$hold->request_lib} || $editor->retrieve_actor_org_unit($hold->request_lib);
2830 $reqr_cache{$hold->requestor} = $reqr;
2831 $org_cache{$hold->request_lib} = $rlib;
2833 # see if this hold is permitted
2834 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2835 { patron_id => $hold->usr,
2838 pickup_lib => $hold->pickup_lib,
2839 request_lib => $rlib,
2851 unless( $best_hold ) { # no "good" permitted holds were found
2852 if( my $hold = $$old_holds[0] ) { # can we return a pre-targeted hold?
2853 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2858 $logger->info("circulator: no suitable holds found for copy $bc");
2859 return (undef, $evt);
2862 $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
2864 # indicate a permitted hold was found
2865 return $best_hold if $check_only;
2867 # we've found a permitted hold. we need to "grab" the copy
2868 # to prevent re-targeted holds (next part) from re-grabbing the copy
2869 $best_hold->current_copy($copy->id);
2870 $editor->update_action_hold_request($best_hold)
2871 or return (undef, $editor->event);
2876 # re-target any other holds that already target this copy
2877 for my $old_hold (@$old_holds) {
2878 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
2879 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
2880 $old_hold->id." after a better hold [".$best_hold->id."] was found");
2881 $old_hold->clear_current_copy;
2882 $old_hold->clear_prev_check_time;
2883 $editor->update_action_hold_request($old_hold)
2884 or return (undef, $editor->event);
2885 push(@retarget, $old_hold->id);
2888 return ($best_hold, undef, (@retarget) ? \@retarget : undef);
2896 __PACKAGE__->register_method(
2897 method => 'all_rec_holds',
2898 api_name => 'open-ils.circ.holds.retrieve_all_from_title',
2902 my( $self, $conn, $auth, $title_id, $args ) = @_;
2904 my $e = new_editor(authtoken=>$auth);
2905 $e->checkauth or return $e->event;
2906 $e->allowed('VIEW_HOLD') or return $e->event;
2909 $args->{fulfillment_time} = undef; # we don't want to see old fulfilled holds
2910 $args->{cancel_time} = undef;
2912 my $resp = { volume_holds => [], copy_holds => [], recall_holds => [], force_holds => [], metarecord_holds => [], part_holds => [], issuance_holds => [] };
2914 my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
2916 $resp->{metarecord_holds} = $e->search_action_hold_request(
2917 { hold_type => OILS_HOLD_TYPE_METARECORD,
2918 target => $mr_map->metarecord,
2924 $resp->{title_holds} = $e->search_action_hold_request(
2926 hold_type => OILS_HOLD_TYPE_TITLE,
2927 target => $title_id,
2931 my $parts = $e->search_biblio_monograph_part(
2937 $resp->{part_holds} = $e->search_action_hold_request(
2939 hold_type => OILS_HOLD_TYPE_MONOPART,
2945 my $subs = $e->search_serial_subscription(
2946 { record_entry => $title_id }, {idlist=>1});
2949 my $issuances = $e->search_serial_issuance(
2950 {subscription => $subs}, {idlist=>1}
2954 $resp->{issuance_holds} = $e->search_action_hold_request(
2956 hold_type => OILS_HOLD_TYPE_ISSUANCE,
2957 target => $issuances,
2964 my $vols = $e->search_asset_call_number(
2965 { record => $title_id, deleted => 'f' }, {idlist=>1});
2967 return $resp unless @$vols;
2969 $resp->{volume_holds} = $e->search_action_hold_request(
2971 hold_type => OILS_HOLD_TYPE_VOLUME,
2976 my $copies = $e->search_asset_copy(
2977 { call_number => $vols, deleted => 'f' }, {idlist=>1});
2979 return $resp unless @$copies;
2981 $resp->{copy_holds} = $e->search_action_hold_request(
2983 hold_type => OILS_HOLD_TYPE_COPY,
2988 $resp->{recall_holds} = $e->search_action_hold_request(
2990 hold_type => OILS_HOLD_TYPE_RECALL,
2995 $resp->{force_holds} = $e->search_action_hold_request(
2997 hold_type => OILS_HOLD_TYPE_FORCE,
3009 __PACKAGE__->register_method(
3010 method => 'uber_hold',
3012 api_name => 'open-ils.circ.hold.details.retrieve'
3016 my($self, $client, $auth, $hold_id, $args) = @_;
3017 my $e = new_editor(authtoken=>$auth);
3018 $e->checkauth or return $e->event;
3019 return uber_hold_impl($e, $hold_id, $args);
3022 __PACKAGE__->register_method(
3023 method => 'batch_uber_hold',
3026 api_name => 'open-ils.circ.hold.details.batch.retrieve'
3029 sub batch_uber_hold {
3030 my($self, $client, $auth, $hold_ids, $args) = @_;
3031 my $e = new_editor(authtoken=>$auth);
3032 $e->checkauth or return $e->event;
3033 $client->respond(uber_hold_impl($e, $_, $args)) for @$hold_ids;
3037 sub uber_hold_impl {
3038 my($e, $hold_id, $args) = @_;
3041 my $hold = $e->retrieve_action_hold_request(
3046 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
3049 ) or return $e->event;
3051 if($hold->usr->id ne $e->requestor->id) {
3052 # A user is allowed to see his/her own holds
3053 $e->allowed('VIEW_HOLD') or return $e->event;
3054 $hold->notes( # filter out any non-staff ("private") notes
3055 [ grep { !$U->is_true($_->staff) } @{$hold->notes} ] );
3058 # caller is asking for own hold, but may not have permission to view staff notes
3059 unless($e->allowed('VIEW_HOLD')) {
3060 $hold->notes( # filter out any staff notes
3061 [ grep { $U->is_true($_->staff) } @{$hold->notes} ] );
3065 my $user = $hold->usr;
3066 $hold->usr($user->id);
3069 my( $mvr, $volume, $copy, $issuance, $part, $bre ) = find_hold_mvr($e, $hold, $args->{suppress_mvr});
3071 flesh_hold_notices([$hold], $e) unless $args->{suppress_notices};
3072 flesh_hold_transits([$hold]) unless $args->{suppress_transits};
3074 my $details = retrieve_hold_queue_status_impl($e, $hold);
3079 ($copy ? (copy => $copy) : ()),
3080 ($volume ? (volume => $volume) : ()),
3081 ($issuance ? (issuance => $issuance) : ()),
3082 ($part ? (part => $part) : ()),
3083 ($args->{include_bre} ? (bre => $bre) : ()),
3084 ($args->{suppress_mvr} ? () : (mvr => $mvr)),
3088 unless($args->{suppress_patron_details}) {
3089 my $card = $e->retrieve_actor_card($user->card) or return $e->event;
3090 $resp->{patron_first} = $user->first_given_name,
3091 $resp->{patron_last} = $user->family_name,
3092 $resp->{patron_barcode} = $card->barcode,
3093 $resp->{patron_alias} = $user->alias,
3101 # -----------------------------------------------------
3102 # Returns the MVR object that represents what the
3104 # -----------------------------------------------------
3106 my( $e, $hold, $no_mvr ) = @_;
3114 if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
3115 my $mr = $e->retrieve_metabib_metarecord($hold->target)
3116 or return $e->event;
3117 $tid = $mr->master_record;
3119 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
3120 $tid = $hold->target;
3122 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
3123 $volume = $e->retrieve_asset_call_number($hold->target)
3124 or return $e->event;
3125 $tid = $volume->record;
3127 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
3128 $issuance = $e->retrieve_serial_issuance([
3130 {flesh => 1, flesh_fields => {siss => [ qw/subscription/ ]}}
3131 ]) or return $e->event;
3133 $tid = $issuance->subscription->record_entry;
3135 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_MONOPART ) {
3136 $part = $e->retrieve_biblio_monograph_part([
3138 ]) or return $e->event;
3140 $tid = $part->record;
3142 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_COPY || $hold->hold_type eq OILS_HOLD_TYPE_RECALL || $hold->hold_type eq OILS_HOLD_TYPE_FORCE ) {
3143 $copy = $e->retrieve_asset_copy([
3145 {flesh => 1, flesh_fields => {acp => ['call_number']}}
3146 ]) or return $e->event;
3148 $volume = $copy->call_number;
3149 $tid = $volume->record;
3152 if(!$copy and ref $hold->current_copy ) {
3153 $copy = $hold->current_copy;
3154 $hold->current_copy($copy->id);
3157 if(!$volume and $copy) {
3158 $volume = $e->retrieve_asset_call_number($copy->call_number);
3161 # TODO return metarcord mvr for M holds
3162 my $title = $e->retrieve_biblio_record_entry($tid);
3163 return ( ($no_mvr) ? undef : $U->record_to_mvr($title), $volume, $copy, $issuance, $part, $title );
3166 __PACKAGE__->register_method(
3167 method => 'clear_shelf_cache',
3168 api_name => 'open-ils.circ.hold.clear_shelf.get_cache',
3172 Returns the holds processed with the given cache key
3177 sub clear_shelf_cache {
3178 my($self, $client, $auth, $cache_key, $chunk_size) = @_;
3179 my $e = new_editor(authtoken => $auth, xact => 1);
3180 return $e->die_event unless $e->checkauth and $e->allowed('VIEW_HOLD');
3183 my $hold_data = OpenSRF::Utils::Cache->new('global')->get_cache($cache_key);
3186 $logger->info("no hold data found in cache"); # XXX TODO return event
3192 foreach (keys %$hold_data) {
3193 $maximum += scalar(@{ $hold_data->{$_} });
3195 $client->respond({"maximum" => $maximum, "progress" => 0});
3197 for my $action (sort keys %$hold_data) {
3198 while (@{$hold_data->{$action}}) {
3199 my @hid_chunk = splice @{$hold_data->{$action}}, 0, $chunk_size;
3201 my $result_chunk = $e->json_query({
3203 "acp" => ["barcode"],
3205 first_given_name second_given_name family_name alias
3208 "acnp" => [{column => "label", alias => "prefix"}],
3209 "acns" => [{column => "label", alias => "suffix"}],
3217 "field" => "id", "fkey" => "current_copy",
3220 "field" => "id", "fkey" => "call_number",
3223 "field" => "id", "fkey" => "record"
3226 "field" => "id", "fkey" => "prefix"
3229 "field" => "id", "fkey" => "suffix"
3233 "acpl" => {"field" => "id", "fkey" => "location"}
3236 "au" => {"field" => "id", "fkey" => "usr"}
3239 "where" => {"+ahr" => {"id" => \@hid_chunk}}
3240 }, {"substream" => 1}) or return $e->die_event;
3244 +{"action" => $action, "hold_details" => $_}
3255 __PACKAGE__->register_method(
3256 method => 'clear_shelf_process',
3258 api_name => 'open-ils.circ.hold.clear_shelf.process',
3261 1. Find all holds that have expired on the holds shelf
3263 3. If a clear-shelf status is configured, put targeted copies into this status
3264 4. Divide copies into 3 groups: items to transit, items to reshelve, and items
3265 that are needed for holds. No subsequent action is taken on the holds
3266 or items after grouping.
3271 sub clear_shelf_process {
3272 my($self, $client, $auth, $org_id, $match_copy) = @_;
3274 my $current_copy = { '!=' => undef };
3275 $current_copy = { '=' => $match_copy } if $match_copy;
3277 my $e = new_editor(authtoken=>$auth, xact => 1);
3278 $e->checkauth or return $e->die_event;
3279 my $cache = OpenSRF::Utils::Cache->new('global');
3281 $org_id ||= $e->requestor->ws_ou;
3282 $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
3284 my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
3286 # Find holds on the shelf that have been there too long
3287 my $hold_ids = $e->search_action_hold_request(
3288 { shelf_expire_time => {'<' => 'now'},
3289 pickup_lib => $org_id,
3290 cancel_time => undef,
3291 fulfillment_time => undef,
3292 shelf_time => {'!=' => undef},
3293 capture_time => {'!=' => undef},
3294 current_copy => $current_copy,
3300 my $chunk_size = 25; # chunked status updates
3302 for my $hold_id (@$hold_ids) {
3304 $logger->info("Clear shelf processing hold $hold_id");
3306 my $hold = $e->retrieve_action_hold_request([
3309 flesh_fields => {ahr => ['current_copy']}
3313 $hold->cancel_time('now');
3314 $hold->cancel_cause(2); # Hold Shelf expiration
3315 $e->update_action_hold_request($hold) or return $e->die_event;
3316 delete_hold_copy_maps($self, $e, $hold->id) and return $e->die_event;
3318 my $copy = $hold->current_copy;
3320 if($copy_status or $copy_status == 0) {
3321 # if a clear-shelf copy status is defined, update the copy
3322 $copy->status($copy_status);
3323 $copy->edit_date('now');
3324 $copy->editor($e->requestor->id);
3325 $e->update_asset_copy($copy) or return $e->die_event;
3328 push(@holds, $hold);
3329 $client->respond({maximum => scalar(@holds), progress => $counter}) if ( (++$counter % $chunk_size) == 0);
3340 for my $hold (@holds) {
3342 my $copy = $hold->current_copy;
3343 my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
3345 if($alt_hold and !$match_copy) {
3347 push(@{$cache_data{hold}}, $hold->id); # copy is needed for a hold
3349 } elsif($copy->circ_lib != $e->requestor->ws_ou) {
3351 push(@{$cache_data{transit}}, $hold->id); # copy needs to transit
3355 push(@{$cache_data{shelf}}, $hold->id); # copy needs to go back to the shelf
3359 my $cache_key = md5_hex(time . $$ . rand());
3360 $logger->info("clear_shelf_cache: storing under $cache_key");
3361 $cache->put_cache($cache_key, \%cache_data, 7200); # TODO: 2 hours. configurable?
3363 # tell the client we're done
3364 $client->respond_complete({cache_key => $cache_key});
3367 # fire off the hold cancelation trigger and wait for response so don't flood the service
3369 # refetch the holds to pick up the caclulated cancel_time,
3370 # which may be needed by Action/Trigger
3372 my $updated_holds = $e->search_action_hold_request({id => $hold_ids}, {substream => 1});
3375 $U->create_events_for_hook(
3376 'hold_request.cancel.expire_holds_shelf',
3377 $_, $org_id, undef, undef, 1) for @$updated_holds;
3380 # tell the client we're done
3381 $client->respond_complete;
3385 __PACKAGE__->register_method(
3386 method => 'usr_hold_summary',
3387 api_name => 'open-ils.circ.holds.user_summary',
3389 Returns a summary of holds statuses for a given user
3393 sub usr_hold_summary {
3394 my($self, $conn, $auth, $user_id) = @_;
3396 my $e = new_editor(authtoken=>$auth);
3397 $e->checkauth or return $e->event;
3398 $e->allowed('VIEW_HOLD') or return $e->event;
3400 my $holds = $e->search_action_hold_request(
3403 fulfillment_time => undef,
3404 cancel_time => undef,
3408 my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
3409 $summary{_hold_status($e, $_)} += 1 for @$holds;
3415 __PACKAGE__->register_method(
3416 method => 'hold_has_copy_at',
3417 api_name => 'open-ils.circ.hold.has_copy_at',
3420 'Returns the ID of the found copy and name of the shelving location if there is ' .
3421 'an available copy at the specified org unit. Returns empty hash otherwise. ' .
3422 'The anticipated use for this method is to determine whether an item is ' .
3423 'available at the library where the user is placing the hold (or, alternatively, '.
3424 'at the pickup library) to encourage bypassing the hold placement and just ' .
3425 'checking out the item.' ,
3427 { desc => 'Authentication Token', type => 'string' },
3428 { desc => 'Method Arguments. Options include: hold_type, hold_target, org_unit. '
3429 . 'hold_type is the hold type code (T, V, C, M, ...). '
3430 . 'hold_target is the identifier of the hold target object. '
3431 . 'org_unit is org unit ID.',
3436 desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
3442 sub hold_has_copy_at {
3443 my($self, $conn, $auth, $args) = @_;
3445 my $e = new_editor(authtoken=>$auth);
3446 $e->checkauth or return $e->event;
3448 my $hold_type = $$args{hold_type};
3449 my $hold_target = $$args{hold_target};
3450 my $org_unit = $$args{org_unit};
3453 select => {acp => ['id'], acpl => ['name']},
3456 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
3457 ccs => {field => 'id', filter => { holdable => 't'}, fkey => 'status' }
3460 where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit}},
3464 if($hold_type eq 'C') {
3466 $query->{where}->{'+acp'}->{id} = $hold_target;
3468 } elsif($hold_type eq 'V') {
3470 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3472 } elsif($hold_type eq 'T') {
3474 $query->{from}->{acp}->{acn} = {
3476 fkey => 'call_number',
3480 filter => {id => $hold_target},
3488 $query->{from}->{acp}->{acn} = {
3490 fkey => 'call_number',
3499 filter => {metarecord => $hold_target},
3507 my $res = $e->json_query($query)->[0] or return {};
3508 return {copy => $res->{id}, location => $res->{name}} if $res;
3512 # returns true if the user already has an item checked out
3513 # that could be used to fulfill the requested hold.
3514 sub hold_item_is_checked_out {
3515 my($e, $user_id, $hold_type, $hold_target) = @_;
3518 select => {acp => ['id']},
3519 from => {acp => {}},
3523 in => { # copies for circs the user has checked out
3524 select => {circ => ['target_copy']},
3528 checkin_time => undef,
3530 {stop_fines => ["MAXFINES","LONGOVERDUE"]},
3531 {stop_fines => undef}
3541 if($hold_type eq 'C' || $hold_type eq 'R' || $hold_type eq 'F') {
3543 $query->{where}->{'+acp'}->{id}->{in}->{where}->{'target_copy'} = $hold_target;
3545 } elsif($hold_type eq 'V') {
3547 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3549 } elsif($hold_type eq 'P') {
3551 $query->{from}->{acp}->{acpm} = {
3552 field => 'target_copy',
3554 filter => {part => $hold_target},
3557 } elsif($hold_type eq 'I') {
3559 $query->{from}->{acp}->{sitem} = {
3562 filter => {issuance => $hold_target},
3565 } elsif($hold_type eq 'T') {
3567 $query->{from}->{acp}->{acn} = {
3569 fkey => 'call_number',
3573 filter => {id => $hold_target},
3581 $query->{from}->{acp}->{acn} = {
3583 fkey => 'call_number',
3592 filter => {metarecord => $hold_target},
3600 return $e->json_query($query)->[0];
3603 __PACKAGE__->register_method(
3604 method => 'change_hold_title',
3605 api_name => 'open-ils.circ.hold.change_title',
3608 Updates all title level holds targeting the specified bibs to point a new bib./,
3610 { desc => 'Authentication Token', type => 'string' },
3611 { desc => 'New Target Bib Id', type => 'number' },
3612 { desc => 'Old Target Bib Ids', type => 'array' },
3614 return => { desc => '1 on success' }
3618 __PACKAGE__->register_method(
3619 method => 'change_hold_title_for_specific_holds',
3620 api_name => 'open-ils.circ.hold.change_title.specific_holds',
3623 Updates specified holds to target new bib./,
3625 { desc => 'Authentication Token', type => 'string' },
3626 { desc => 'New Target Bib Id', type => 'number' },
3627 { desc => 'Holds Ids for holds to update', type => 'array' },
3629 return => { desc => '1 on success' }
3634 sub change_hold_title {
3635 my( $self, $client, $auth, $new_bib_id, $bib_ids ) = @_;
3637 my $e = new_editor(authtoken=>$auth, xact=>1);
3638 return $e->die_event unless $e->checkauth;
3640 my $holds = $e->search_action_hold_request(
3643 cancel_time => undef,
3644 fulfillment_time => undef,
3650 flesh_fields => { ahr => ['usr'] }
3656 for my $hold (@$holds) {
3657 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3658 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3659 $hold->target( $new_bib_id );
3660 $e->update_action_hold_request($hold) or return $e->die_event;
3665 _reset_hold($self, $e->requestor, $_) for @$holds;
3670 sub change_hold_title_for_specific_holds {
3671 my( $self, $client, $auth, $new_bib_id, $hold_ids ) = @_;
3673 my $e = new_editor(authtoken=>$auth, xact=>1);
3674 return $e->die_event unless $e->checkauth;
3676 my $holds = $e->search_action_hold_request(
3679 cancel_time => undef,
3680 fulfillment_time => undef,
3686 flesh_fields => { ahr => ['usr'] }
3692 for my $hold (@$holds) {
3693 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3694 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3695 $hold->target( $new_bib_id );
3696 $e->update_action_hold_request($hold) or return $e->die_event;
3701 _reset_hold($self, $e->requestor, $_) for @$holds;
3706 __PACKAGE__->register_method(
3707 method => 'rec_hold_count',
3708 api_name => 'open-ils.circ.bre.holds.count',
3710 desc => q/Returns the total number of holds that target the
3711 selected bib record or its associated copies and call_numbers/,
3713 { desc => 'Bib ID', type => 'number' },
3715 return => {desc => 'Hold count', type => 'number'}
3719 __PACKAGE__->register_method(
3720 method => 'rec_hold_count',
3721 api_name => 'open-ils.circ.mmr.holds.count',
3723 desc => q/Returns the total number of holds that target the
3724 selected metarecord or its associated copies, call_numbers, and bib records/,
3726 { desc => 'Metarecord ID', type => 'number' },
3728 return => {desc => 'Hold count', type => 'number'}
3732 # XXX Need to add type I (and, soon, type P) holds to these counts
3733 sub rec_hold_count {
3734 my($self, $conn, $target_id) = @_;
3741 filter => {metarecord => $target_id}
3748 filter => { id => $target_id },
3753 if($self->api_name =~ /mmr/) {
3754 delete $bre_join->{bre}->{filter};
3755 $bre_join->{bre}->{join} = $mmr_join;
3761 fkey => 'call_number',
3767 select => {ahr => [{column => 'id', transform => 'count', alias => 'count'}]},
3771 cancel_time => undef,
3772 fulfillment_time => undef,
3776 hold_type => [qw/C F R/],
3779 select => {acp => ['id']},
3780 from => { acp => $cn_join }
3790 select => {acn => ['id']},
3791 from => {acn => $bre_join}
3799 target => $target_id
3807 if($self->api_name =~ /mmr/) {
3808 $query->{where}->{'+ahr'}->{'-or'}->[2] = {
3813 select => {bre => ['id']},
3814 from => {bre => $mmr_join}
3820 $query->{where}->{'+ahr'}->{'-or'}->[3] = {
3823 target => $target_id
3829 return new_editor()->json_query($query)->[0]->{count};