1 # ---------------------------------------------------------------
2 # Copyright (C) 2005 Georgia Public Library Service
3 # Bill Erickson <highfalutin@gmail.com>
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 # ---------------------------------------------------------------
17 package OpenILS::Application::Circ::Holds;
18 use base qw/OpenILS::Application/;
19 use strict; use warnings;
20 use OpenILS::Application::AppUtils;
23 use OpenSRF::EX qw(:try);
27 use OpenSRF::Utils::Logger qw(:logger);
28 use OpenILS::Utils::CStoreEditor q/:funcs/;
29 use OpenILS::Utils::PermitHold;
30 use OpenSRF::Utils::SettingsClient;
31 use OpenILS::Const qw/:const/;
32 use OpenILS::Application::Circ::Transit;
33 use OpenILS::Application::Actor::Friends;
35 use DateTime::Format::ISO8601;
36 use OpenSRF::Utils qw/:datetime/;
37 use Digest::MD5 qw(md5_hex);
38 use OpenSRF::Utils::Cache;
39 my $apputils = "OpenILS::Application::AppUtils";
42 __PACKAGE__->register_method(
43 method => "test_and_create_hold_batch",
44 api_name => "open-ils.circ.holds.test_and_create.batch",
47 desc => q/This is for batch creating a set of holds where every field is identical except for the targets./,
49 { desc => 'Authentication token', type => 'string' },
50 { desc => 'Hash of named parameters. Same as for open-ils.circ.title_hold.is_possible, though the pertinent target field is automatically populated based on the hold_type and the specified list of targets.', type => 'object'},
51 { desc => 'Array of target ids', type => 'array' }
54 desc => 'Array of hold ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
59 __PACKAGE__->register_method(
60 method => "test_and_create_hold_batch",
61 api_name => "open-ils.circ.holds.test_and_create.batch.override",
64 desc => '@see open-ils.circ.holds.test_and_create.batch',
69 sub test_and_create_hold_batch {
70 my( $self, $conn, $auth, $params, $target_list, $oargs ) = @_;
72 my $override = 1 if $self->api_name =~ /override/;
73 $oargs = { all => 1 } unless defined $oargs;
75 my $e = new_editor(authtoken=>$auth);
76 return $e->die_event unless $e->checkauth;
77 $$params{'requestor'} = $e->requestor->id;
80 if ($$params{'hold_type'} eq 'T') { $target_field = 'titleid'; }
81 elsif ($$params{'hold_type'} eq 'C') { $target_field = 'copy_id'; }
82 elsif ($$params{'hold_type'} eq 'R') { $target_field = 'copy_id'; }
83 elsif ($$params{'hold_type'} eq 'F') { $target_field = 'copy_id'; }
84 elsif ($$params{'hold_type'} eq 'I') { $target_field = 'issuanceid'; }
85 elsif ($$params{'hold_type'} eq 'V') { $target_field = 'volume_id'; }
86 elsif ($$params{'hold_type'} eq 'M') { $target_field = 'mrid'; }
87 elsif ($$params{'hold_type'} eq 'P') { $target_field = 'partid'; }
88 else { return undef; }
90 foreach (@$target_list) {
91 $$params{$target_field} = $_;
93 ($res) = $self->method_lookup(
94 'open-ils.circ.title_hold.is_possible')->run($auth, $params, $override ? $oargs : {});
95 if ($res->{'success'} == 1) {
96 my $ahr = construct_hold_request_object($params);
97 my ($res2) = $self->method_lookup(
99 ? 'open-ils.circ.holds.create.override'
100 : 'open-ils.circ.holds.create'
101 )->run($auth, $ahr, $oargs);
103 'target' => $$params{$target_field},
106 $conn->respond($res2);
109 'target' => $$params{$target_field},
112 $conn->respond($res);
118 sub construct_hold_request_object {
121 my $ahr = Fieldmapper::action::hold_request->new;
124 foreach my $field (keys %{ $params }) {
125 if ($field eq 'depth') { $ahr->selection_depth($$params{$field}); }
126 elsif ($field eq 'patronid') {
127 $ahr->usr($$params{$field}); }
128 elsif ($field eq 'titleid') { $ahr->target($$params{$field}); }
129 elsif ($field eq 'copy_id') { $ahr->target($$params{$field}); }
130 elsif ($field eq 'issuanceid') { $ahr->target($$params{$field}); }
131 elsif ($field eq 'volume_id') { $ahr->target($$params{$field}); }
132 elsif ($field eq 'mrid') { $ahr->target($$params{$field}); }
133 elsif ($field eq 'partid') { $ahr->target($$params{$field}); }
135 $ahr->$field($$params{$field});
141 __PACKAGE__->register_method(
142 method => "create_hold_batch",
143 api_name => "open-ils.circ.holds.create.batch",
146 desc => q/@see open-ils.circ.holds.create.batch/,
148 { desc => 'Authentication token', type => 'string' },
149 { desc => 'Array of hold objects', type => 'array' }
152 desc => 'Array of hold ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
157 __PACKAGE__->register_method(
158 method => "create_hold_batch",
159 api_name => "open-ils.circ.holds.create.override.batch",
162 desc => '@see open-ils.circ.holds.create.batch',
167 sub create_hold_batch {
168 my( $self, $conn, $auth, $hold_list, $oargs ) = @_;
169 (my $method = $self->api_name) =~ s/\.batch//og;
170 foreach (@$hold_list) {
171 my ($res) = $self->method_lookup($method)->run($auth, $_, $oargs);
172 $conn->respond($res);
178 __PACKAGE__->register_method(
179 method => "create_hold",
180 api_name => "open-ils.circ.holds.create",
182 desc => "Create a new hold for an item. From a permissions perspective, " .
183 "the login session is used as the 'requestor' of the hold. " .
184 "The hold recipient is determined by the 'usr' setting within the hold object. " .
185 'First we verify the requestor has holds request permissions. ' .
186 'Then we verify that the recipient is allowed to make the given hold. ' .
187 'If not, we see if the requestor has "override" capabilities. If not, ' .
188 'a permission exception is returned. If permissions allow, we cycle ' .
189 'through the set of holds objects and create. ' .
190 'If the recipient does not have permission to place multiple holds ' .
191 'on a single title and said operation is attempted, a permission ' .
192 'exception is returned',
194 { desc => 'Authentication token', type => 'string' },
195 { desc => 'Hold object for hold to be created',
196 type => 'object', class => 'ahr' }
199 desc => 'New ahr ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
204 __PACKAGE__->register_method(
205 method => "create_hold",
206 api_name => "open-ils.circ.holds.create.override",
207 notes => '@see open-ils.circ.holds.create',
209 desc => "If the recipient is not allowed to receive the requested hold, " .
210 "call this method to attempt the override",
212 { desc => 'Authentication token', type => 'string' },
214 desc => 'Hold object for hold to be created',
215 type => 'object', class => 'ahr'
219 desc => 'New hold (ahr) ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
225 my( $self, $conn, $auth, $hold, $oargs ) = @_;
226 return -1 unless $hold;
227 my $e = new_editor(authtoken=>$auth, xact=>1);
228 return $e->die_event unless $e->checkauth;
230 my $override = 1 if $self->api_name =~ /override/;
231 $oargs = { all => 1 } unless defined $oargs;
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 || $t eq OILS_HOLD_TYPE_RECALL ) {
292 my $copy = $e->retrieve_asset_copy($hold->target)
293 or return $e->die_event;
294 if ( $t eq OILS_HOLD_TYPE_FORCE ) {
295 return $e->die_event unless $e->allowed('COPY_HOLDS_FORCE', $copy->circ_lib);
296 } elsif ( $t eq OILS_HOLD_TYPE_RECALL ) {
297 return $e->die_event unless $e->allowed('COPY_HOLDS_RECALL', $copy->circ_lib);
306 for my $evt (@events) {
308 my $name = $evt->{textcode};
309 if($oargs->{all} || grep { $_ eq $name } @{$oargs->{events}}) {
310 return $e->die_event unless $e->allowed("$name.override", $porg);
318 # set the configured expire time
319 unless($hold->expire_time) {
320 my $interval = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_HOLD_EXPIRE);
322 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
323 $hold->expire_time($U->epoch2ISO8601($date->epoch));
327 $hold->requestor($e->requestor->id);
328 $hold->request_lib($e->requestor->ws_ou);
329 $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
330 $hold = $e->create_action_hold_request($hold) or return $e->die_event;
334 $conn->respond_complete($hold->id);
337 'open-ils.storage.action.hold_request.copy_targeter',
338 undef, $hold->id ) unless $U->is_true($hold->frozen);
343 # makes sure that a user has permission to place the type of requested hold
344 # returns the Perm exception if not allowed, returns undef if all is well
345 sub _check_holds_perm {
346 my($type, $user_id, $org_id) = @_;
350 $evt = $apputils->check_perms($user_id, $org_id, "MR_HOLDS" );
351 } elsif ($type eq "T") {
352 $evt = $apputils->check_perms($user_id, $org_id, "TITLE_HOLDS" );
353 } elsif($type eq "V") {
354 $evt = $apputils->check_perms($user_id, $org_id, "VOLUME_HOLDS");
355 } elsif($type eq "C") {
356 $evt = $apputils->check_perms($user_id, $org_id, "COPY_HOLDS" );
363 # tests if the given user is allowed to place holds on another's behalf
364 sub _check_request_holds_perm {
367 if (my $evt = $apputils->check_perms(
368 $user_id, $org_id, "REQUEST_HOLDS")) {
373 my $ses_is_req_note = 'The login session is the requestor. If the requestor is different from the user, ' .
374 'then the requestor must have VIEW_HOLD permissions';
376 __PACKAGE__->register_method(
377 method => "retrieve_holds_by_id",
378 api_name => "open-ils.circ.holds.retrieve_by_id",
380 desc => "Retrieve the hold, with hold transits attached, for the specified ID. $ses_is_req_note",
382 { desc => 'Authentication token', type => 'string' },
383 { desc => 'Hold ID', type => 'number' }
386 desc => 'Hold object with transits attached, event on error',
392 sub retrieve_holds_by_id {
393 my($self, $client, $auth, $hold_id) = @_;
394 my $e = new_editor(authtoken=>$auth);
395 $e->checkauth or return $e->event;
396 $e->allowed('VIEW_HOLD') or return $e->event;
398 my $holds = $e->search_action_hold_request(
400 { id => $hold_id , fulfillment_time => undef },
402 order_by => { ahr => "request_time" },
404 flesh_fields => {ahr => ['notes']}
409 flesh_hold_transits($holds);
410 flesh_hold_notices($holds, $e);
415 __PACKAGE__->register_method(
416 method => "retrieve_holds",
417 api_name => "open-ils.circ.holds.retrieve",
419 desc => "Retrieves all the holds, with hold transits attached, for the specified user. $ses_is_req_note",
421 { desc => 'Authentication token', type => 'string' },
422 { desc => 'User ID', type => 'integer' }
425 desc => 'list of holds, event on error',
430 __PACKAGE__->register_method(
431 method => "retrieve_holds",
432 api_name => "open-ils.circ.holds.id_list.retrieve",
435 desc => "Retrieves all the hold IDs, for the specified user. $ses_is_req_note",
437 { desc => 'Authentication token', type => 'string' },
438 { desc => 'User ID', type => 'integer' }
441 desc => 'list of holds, event on error',
446 __PACKAGE__->register_method(
447 method => "retrieve_holds",
448 api_name => "open-ils.circ.holds.canceled.retrieve",
451 desc => "Retrieves all the cancelled holds for the specified user. $ses_is_req_note",
453 { desc => 'Authentication token', type => 'string' },
454 { desc => 'User ID', type => 'integer' }
457 desc => 'list of holds, event on error',
462 __PACKAGE__->register_method(
463 method => "retrieve_holds",
464 api_name => "open-ils.circ.holds.canceled.id_list.retrieve",
467 desc => "Retrieves list of cancelled hold IDs for the specified user. $ses_is_req_note",
469 { desc => 'Authentication token', type => 'string' },
470 { desc => 'User ID', type => 'integer' }
473 desc => 'list of hold IDs, event on error',
480 my ($self, $client, $auth, $user_id) = @_;
482 my $e = new_editor(authtoken=>$auth);
483 return $e->event unless $e->checkauth;
484 $user_id = $e->requestor->id unless defined $user_id;
486 my $notes_filter = {staff => 'f'};
487 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
488 unless($user_id == $e->requestor->id) {
489 if($e->allowed('VIEW_HOLD', $user->home_ou)) {
490 $notes_filter = {staff => 't'}
492 my $allowed = OpenILS::Application::Actor::Friends->friend_perm_allowed(
493 $e, $user_id, $e->requestor->id, 'hold.view');
494 return $e->event unless $allowed;
497 # staff member looking at his/her own holds can see staff and non-staff notes
498 $notes_filter = {} if $e->allowed('VIEW_HOLD', $user->home_ou);
502 select => {ahr => ['id']},
504 where => {usr => $user_id, fulfillment_time => undef}
507 if($self->api_name =~ /canceled/) {
509 # Fetch the canceled holds
510 # order cancelled holds by cancel time, most recent first
512 $holds_query->{order_by} = [{class => 'ahr', field => 'cancel_time', direction => 'desc'}];
515 my $cancel_count = $U->ou_ancestor_setting_value(
516 $e->requestor->ws_ou, 'circ.holds.canceled.display_count', $e);
518 unless($cancel_count) {
519 $cancel_age = $U->ou_ancestor_setting_value(
520 $e->requestor->ws_ou, 'circ.holds.canceled.display_age', $e);
522 # if no settings are defined, default to last 10 cancelled holds
523 $cancel_count = 10 unless $cancel_age;
526 if($cancel_count) { # limit by count
528 $holds_query->{where}->{cancel_time} = {'!=' => undef};
529 $holds_query->{limit} = $cancel_count;
531 } elsif($cancel_age) { # limit by age
533 # find all of the canceled holds that were canceled within the configured time frame
534 my $date = DateTime->now->subtract(seconds => OpenSRF::Utils::interval_to_seconds($cancel_age));
535 $date = $U->epoch2ISO8601($date->epoch);
536 $holds_query->{where}->{cancel_time} = {'>=' => $date};
541 # order non-cancelled holds by ready-for-pickup, then active, followed by suspended
542 # "compare" sorts false values to the front. testing pickup_lib != current_shelf_lib
543 # will sort by pl = csl > pl != csl > followed by csl is null;
544 $holds_query->{order_by} = [
546 field => 'pickup_lib',
547 compare => {'!=' => {'+ahr' => 'current_shelf_lib'}}},
548 {class => 'ahr', field => 'shelf_time'},
549 {class => 'ahr', field => 'frozen'},
550 {class => 'ahr', field => 'request_time'}
553 $holds_query->{where}->{cancel_time} = undef;
556 my $hold_ids = $e->json_query($holds_query);
557 $hold_ids = [ map { $_->{id} } @$hold_ids ];
559 return $hold_ids if $self->api_name =~ /id_list/;
562 for my $hold_id ( @$hold_ids ) {
564 my $hold = $e->retrieve_action_hold_request($hold_id);
565 $hold->notes($e->search_action_hold_request_note({hold => $hold_id, %$notes_filter}));
568 $e->search_action_hold_transit_copy([
570 {order_by => {ahtc => 'source_send_time desc'}, limit => 1}])->[0]
580 __PACKAGE__->register_method(
581 method => 'user_hold_count',
582 api_name => 'open-ils.circ.hold.user.count'
585 sub user_hold_count {
586 my ( $self, $conn, $auth, $userid ) = @_;
587 my $e = new_editor( authtoken => $auth );
588 return $e->event unless $e->checkauth;
589 my $patron = $e->retrieve_actor_user($userid)
591 return $e->event unless $e->allowed( 'VIEW_HOLD', $patron->home_ou );
592 return __user_hold_count( $self, $e, $userid );
595 sub __user_hold_count {
596 my ( $self, $e, $userid ) = @_;
597 my $holds = $e->search_action_hold_request(
600 fulfillment_time => undef,
601 cancel_time => undef,
606 return scalar(@$holds);
610 __PACKAGE__->register_method(
611 method => "retrieve_holds_by_pickup_lib",
612 api_name => "open-ils.circ.holds.retrieve_by_pickup_lib",
614 "Retrieves all the holds, with hold transits attached, for the specified pickup_ou id."
617 __PACKAGE__->register_method(
618 method => "retrieve_holds_by_pickup_lib",
619 api_name => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
620 notes => "Retrieves all the hold ids for the specified pickup_ou id. "
623 sub retrieve_holds_by_pickup_lib {
624 my ($self, $client, $login_session, $ou_id) = @_;
626 #FIXME -- put an appropriate permission check here
627 #my( $user, $target, $evt ) = $apputils->checkses_requestor(
628 # $login_session, $user_id, 'VIEW_HOLD' );
629 #return $evt if $evt;
631 my $holds = $apputils->simplereq(
633 "open-ils.cstore.direct.action.hold_request.search.atomic",
635 pickup_lib => $ou_id ,
636 fulfillment_time => undef,
639 { order_by => { ahr => "request_time" } }
642 if ( ! $self->api_name =~ /id_list/ ) {
643 flesh_hold_transits($holds);
647 return [ map { $_->id } @$holds ];
651 __PACKAGE__->register_method(
652 method => "uncancel_hold",
653 api_name => "open-ils.circ.hold.uncancel"
657 my($self, $client, $auth, $hold_id) = @_;
658 my $e = new_editor(authtoken=>$auth, xact=>1);
659 return $e->die_event unless $e->checkauth;
661 my $hold = $e->retrieve_action_hold_request($hold_id)
662 or return $e->die_event;
663 return $e->die_event unless $e->allowed('CANCEL_HOLDS', $hold->request_lib);
665 if ($hold->fulfillment_time) {
669 unless ($hold->cancel_time) {
674 # if configured to reset the request time, also reset the expire time
675 if($U->ou_ancestor_setting_value(
676 $hold->request_lib, 'circ.holds.uncancel.reset_request_time', $e)) {
678 $hold->request_time('now');
679 my $interval = $U->ou_ancestor_setting_value($hold->request_lib, OILS_SETTING_HOLD_EXPIRE);
681 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
682 $hold->expire_time($U->epoch2ISO8601($date->epoch));
686 $hold->clear_cancel_time;
687 $hold->clear_cancel_cause;
688 $hold->clear_cancel_note;
689 $hold->clear_shelf_time;
690 $hold->clear_current_copy;
691 $hold->clear_capture_time;
692 $hold->clear_prev_check_time;
693 $hold->clear_shelf_expire_time;
694 $hold->clear_current_shelf_lib;
696 $e->update_action_hold_request($hold) or return $e->die_event;
699 $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
705 __PACKAGE__->register_method(
706 method => "cancel_hold",
707 api_name => "open-ils.circ.hold.cancel",
709 desc => 'Cancels the specified hold. The login session is the requestor. If the requestor is different from the usr field ' .
710 'on the hold, the requestor must have CANCEL_HOLDS permissions. The hold may be either the hold object or the hold id',
712 {desc => 'Authentication token', type => 'string'},
713 {desc => 'Hold ID', type => 'number'},
714 {desc => 'Cause of Cancellation', type => 'string'},
715 {desc => 'Note', type => 'string'}
718 desc => '1 on success, event on error'
724 my($self, $client, $auth, $holdid, $cause, $note) = @_;
726 my $e = new_editor(authtoken=>$auth, xact=>1);
727 return $e->die_event unless $e->checkauth;
729 my $hold = $e->retrieve_action_hold_request($holdid)
730 or return $e->die_event;
732 if( $e->requestor->id ne $hold->usr ) {
733 return $e->die_event unless $e->allowed('CANCEL_HOLDS');
736 if ($hold->cancel_time) {
741 # If the hold is captured, reset the copy status
742 if( $hold->capture_time and $hold->current_copy ) {
744 my $copy = $e->retrieve_asset_copy($hold->current_copy)
745 or return $e->die_event;
747 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
748 $logger->info("canceling hold $holdid whose item is on the holds shelf");
749 # $logger->info("setting copy to status 'reshelving' on hold cancel");
750 # $copy->status(OILS_COPY_STATUS_RESHELVING);
751 # $copy->editor($e->requestor->id);
752 # $copy->edit_date('now');
753 # $e->update_asset_copy($copy) or return $e->event;
755 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
758 $logger->warn("! canceling hold [$hid] that is in transit");
759 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
762 my $trans = $e->retrieve_action_transit_copy($transid);
763 # Leave the transit alive, but set the copy status to
764 # reshelving so it will be properly reshelved when it gets back home
766 $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
767 $e->update_action_transit_copy($trans) or return $e->die_event;
773 $hold->cancel_time('now');
774 $hold->cancel_cause($cause);
775 $hold->cancel_note($note);
776 $e->update_action_hold_request($hold)
777 or return $e->die_event;
779 delete_hold_copy_maps($self, $e, $hold->id);
783 # re-fetch the hold to pick up the real cancel_time (not "now") for A/T
785 $hold = $e->retrieve_action_hold_request($hold->id) or return $e->die_event;
788 if ($e->requestor->id == $hold->usr) {
789 $U->create_events_for_hook('hold_request.cancel.patron', $hold, $hold->pickup_lib);
791 $U->create_events_for_hook('hold_request.cancel.staff', $hold, $hold->pickup_lib);
797 sub delete_hold_copy_maps {
802 my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
804 $editor->delete_action_hold_copy_map($_)
805 or return $editor->event;
811 my $update_hold_desc = 'The login session is the requestor. ' .
812 'If the requestor is different from the usr field on the hold, ' .
813 'the requestor must have UPDATE_HOLDS permissions. ' .
814 'If supplying a hash of hold data, "id" must be included. ' .
815 'The hash is ignored if a hold object is supplied, ' .
816 'so you should supply only one kind of hold data argument.' ;
818 __PACKAGE__->register_method(
819 method => "update_hold",
820 api_name => "open-ils.circ.hold.update",
822 desc => "Updates the specified hold. $update_hold_desc",
824 {desc => 'Authentication token', type => 'string'},
825 {desc => 'Hold Object', type => 'object'},
826 {desc => 'Hash of values to be applied', type => 'object'}
829 desc => 'Hold ID on success, event on error',
835 __PACKAGE__->register_method(
836 method => "batch_update_hold",
837 api_name => "open-ils.circ.hold.update.batch",
840 desc => "Updates the specified hold(s). $update_hold_desc",
842 {desc => 'Authentication token', type => 'string'},
843 {desc => 'Array of hold obejcts', type => 'array' },
844 {desc => 'Array of hashes of values to be applied', type => 'array' }
847 desc => 'Hold ID per success, event per error',
853 my($self, $client, $auth, $hold, $values) = @_;
854 my $e = new_editor(authtoken=>$auth, xact=>1);
855 return $e->die_event unless $e->checkauth;
856 my $resp = update_hold_impl($self, $e, $hold, $values);
857 if ($U->event_code($resp)) {
861 $e->commit; # FIXME: update_hold_impl already does $e->commit ??
865 sub batch_update_hold {
866 my($self, $client, $auth, $hold_list, $values_list) = @_;
867 my $e = new_editor(authtoken=>$auth);
868 return $e->die_event unless $e->checkauth;
870 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.
872 $values_list ||= []; # FIXME: either move this above $count declaration, or send an event if both lists undef. Probably the latter.
874 # FIXME: Failing over to [] guarantees warnings for "Use of unitialized value" in update_hold_impl call.
875 # FIXME: We should be sure we only call update_hold_impl with hold object OR hash, not both.
877 for my $idx (0..$count-1) {
879 my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
880 $e->xact_commit unless $U->event_code($resp);
881 $client->respond($resp);
885 return undef; # not in the register return type, assuming we should always have at least one list populated
888 sub update_hold_impl {
889 my($self, $e, $hold, $values) = @_;
891 my $need_retarget = 0;
894 $hold = $e->retrieve_action_hold_request($values->{id})
895 or return $e->die_event;
896 for my $k (keys %$values) {
897 # Outside of pickup_lib (covered by the first regex) I don't know when these would currently change.
898 # But hey, why not cover things that may happen later?
899 if ($k =~ '_(lib|ou)$' || $k eq 'target' || $k eq 'hold_type' || $k eq 'requestor' || $k eq 'selection_depth' || $k eq 'holdable_formats') {
900 if (defined $values->{$k} && defined $hold->$k() && $values->{$k} ne $hold->$k()) {
901 # Value changed? RETARGET!
903 } elsif (defined $hold->$k() != defined $values->{$k}) {
904 # Value being set or cleared? RETARGET!
908 if (defined $values->{$k}) {
909 $hold->$k($values->{$k});
911 my $f = "clear_$k"; $hold->$f();
916 my $orig_hold = $e->retrieve_action_hold_request($hold->id)
917 or return $e->die_event;
919 # don't allow the user to be changed
920 return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
922 if($hold->usr ne $e->requestor->id) {
923 # if the hold is for a different user, make sure the
924 # requestor has the appropriate permissions
925 my $usr = $e->retrieve_actor_user($hold->usr)
926 or return $e->die_event;
927 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
931 # --------------------------------------------------------------
932 # Changing the request time is like playing God
933 # --------------------------------------------------------------
934 if($hold->request_time ne $orig_hold->request_time) {
935 return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
936 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
940 # --------------------------------------------------------------
941 # Code for making sure staff have appropriate permissons for cut_in_line
942 # This, as is, doesn't prevent a user from cutting their own holds in line
944 # --------------------------------------------------------------
945 if($U->is_true($hold->cut_in_line) ne $U->is_true($orig_hold->cut_in_line)) {
946 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
950 # --------------------------------------------------------------
951 # Disallow hold suspencion if the hold is already captured.
952 # --------------------------------------------------------------
953 if ($U->is_true($hold->frozen) and not $U->is_true($orig_hold->frozen)) {
954 $hold_status = _hold_status($e, $hold);
955 if ($hold_status > 2 && $hold_status != 7) { # hold is captured
956 $logger->info("bypassing hold freeze on captured hold");
957 return OpenILS::Event->new('HOLD_SUSPEND_AFTER_CAPTURE');
962 # --------------------------------------------------------------
963 # if the hold is on the holds shelf or in transit and the pickup
964 # lib changes we need to create a new transit.
965 # --------------------------------------------------------------
966 if($orig_hold->pickup_lib ne $hold->pickup_lib) {
968 $hold_status = _hold_status($e, $hold) unless $hold_status;
970 if($hold_status == 3) { # in transit
972 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
973 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
975 $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
977 # update the transit to reflect the new pickup location
978 my $transit = $e->search_action_hold_transit_copy(
979 {hold=>$hold->id, dest_recv_time => undef})->[0]
980 or return $e->die_event;
982 $transit->prev_dest($transit->dest); # mark the previous destination on the transit
983 $transit->dest($hold->pickup_lib);
984 $e->update_action_hold_transit_copy($transit) or return $e->die_event;
986 } elsif($hold_status == 4 or $hold_status == 5 or $hold_status == 8) { # on holds shelf
988 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
989 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
991 $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
993 if ($hold->pickup_lib eq $orig_hold->current_shelf_lib) {
994 # This can happen if the pickup lib is changed while the hold is
995 # on the shelf, then changed back to the original pickup lib.
996 # Restore the original shelf_expire_time to prevent abuse.
997 set_hold_shelf_expire_time(undef, $hold, $e, $hold->shelf_time);
1000 # clear to prevent premature shelf expiration
1001 $hold->clear_shelf_expire_time;
1006 update_hold_if_frozen($self, $e, $hold, $orig_hold);
1007 $e->update_action_hold_request($hold) or return $e->die_event;
1010 # a change to mint-condition changes the set of potential copies, so retarget the hold;
1011 if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
1012 _reset_hold($self, $e->requestor, $hold)
1013 } elsif($need_retarget && !defined $hold->capture_time()) { # If needed, retarget the hold due to changes
1015 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1021 # this does not update the hold in the DB. It only
1022 # sets the shelf_expire_time field on the hold object.
1023 # start_time is optional and defaults to 'now'
1024 sub set_hold_shelf_expire_time {
1025 my ($class, $hold, $editor, $start_time) = @_;
1027 my $shelf_expire = $U->ou_ancestor_setting_value(
1029 'circ.holds.default_shelf_expire_interval',
1033 return undef unless $shelf_expire;
1035 $start_time = ($start_time) ?
1036 DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time)) :
1039 my $seconds = OpenSRF::Utils->interval_to_seconds($shelf_expire);
1040 my $expire_time = $start_time->add(seconds => $seconds);
1042 # if the shelf expire time overlaps with a pickup lib's
1043 # closed date, push it out to the first open date
1044 my $dateinfo = $U->storagereq(
1045 'open-ils.storage.actor.org_unit.closed_date.overlap',
1046 $hold->pickup_lib, $expire_time->strftime('%FT%T%z'));
1049 my $dt_parser = DateTime::Format::ISO8601->new;
1050 $expire_time = $dt_parser->parse_datetime(cleanse_ISO8601($dateinfo->{end}));
1052 # TODO: enable/disable time bump via setting?
1053 $expire_time->set(hour => '23', minute => '59', second => '59');
1055 $logger->info("circulator: shelf_expire_time overlaps".
1056 " with closed date, pushing expire time to $expire_time");
1059 $hold->shelf_expire_time($expire_time->strftime('%FT%T%z'));
1065 my($e, $orig_hold, $hold, $copy) = @_;
1066 my $src = $orig_hold->pickup_lib;
1067 my $dest = $hold->pickup_lib;
1069 $logger->info("putting hold into transit on pickup_lib update");
1071 my $transit = Fieldmapper::action::hold_transit_copy->new;
1072 $transit->hold($hold->id);
1073 $transit->source($src);
1074 $transit->dest($dest);
1075 $transit->target_copy($copy->id);
1076 $transit->source_send_time('now');
1077 $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
1079 $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
1080 $copy->editor($e->requestor->id);
1081 $copy->edit_date('now');
1083 $e->create_action_hold_transit_copy($transit) or return $e->die_event;
1084 $e->update_asset_copy($copy) or return $e->die_event;
1088 # if the hold is frozen, this method ensures that the hold is not "targeted",
1089 # that is, it clears the current_copy and prev_check_time to essentiallly
1090 # reset the hold. If it is being activated, it runs the targeter in the background
1091 sub update_hold_if_frozen {
1092 my($self, $e, $hold, $orig_hold) = @_;
1093 return if $hold->capture_time;
1095 if($U->is_true($hold->frozen)) {
1096 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
1097 $hold->clear_current_copy;
1098 $hold->clear_prev_check_time;
1101 if($U->is_true($orig_hold->frozen)) {
1102 $logger->info("Running targeter on activated hold ".$hold->id);
1103 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1108 __PACKAGE__->register_method(
1109 method => "hold_note_CUD",
1110 api_name => "open-ils.circ.hold_request.note.cud",
1112 desc => 'Create, update or delete a hold request note. If the operator (from Auth. token) '
1113 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
1115 { desc => 'Authentication token', type => 'string' },
1116 { desc => 'Hold note object', type => 'object' }
1119 desc => 'Returns the note ID, event on error'
1125 my($self, $conn, $auth, $note) = @_;
1127 my $e = new_editor(authtoken => $auth, xact => 1);
1128 return $e->die_event unless $e->checkauth;
1130 my $hold = $e->retrieve_action_hold_request($note->hold)
1131 or return $e->die_event;
1133 if($hold->usr ne $e->requestor->id) {
1134 my $usr = $e->retrieve_actor_user($hold->usr);
1135 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
1136 $note->staff('t') if $note->isnew;
1140 $e->create_action_hold_request_note($note) or return $e->die_event;
1141 } elsif($note->ischanged) {
1142 $e->update_action_hold_request_note($note) or return $e->die_event;
1143 } elsif($note->isdeleted) {
1144 $e->delete_action_hold_request_note($note) or return $e->die_event;
1152 __PACKAGE__->register_method(
1153 method => "retrieve_hold_status",
1154 api_name => "open-ils.circ.hold.status.retrieve",
1156 desc => 'Calculates the current status of the hold. The requestor must have ' .
1157 'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
1159 { desc => 'Hold ID', type => 'number' }
1162 # type => 'number', # event sometimes
1163 desc => <<'END_OF_DESC'
1164 Returns event on error or:
1165 -1 on error (for now),
1166 1 for 'waiting for copy to become available',
1167 2 for 'waiting for copy capture',
1170 5 for 'hold-shelf-delay'
1173 8 for 'captured, on wrong hold shelf'
1179 sub retrieve_hold_status {
1180 my($self, $client, $auth, $hold_id) = @_;
1182 my $e = new_editor(authtoken => $auth);
1183 return $e->event unless $e->checkauth;
1184 my $hold = $e->retrieve_action_hold_request($hold_id)
1185 or return $e->event;
1187 if( $e->requestor->id != $hold->usr ) {
1188 return $e->event unless $e->allowed('VIEW_HOLD');
1191 return _hold_status($e, $hold);
1197 if ($hold->cancel_time) {
1200 if ($U->is_true($hold->frozen) && !$hold->capture_time) {
1203 if ($hold->current_shelf_lib and $hold->current_shelf_lib ne $hold->pickup_lib) {
1206 return 1 unless $hold->current_copy;
1207 return 2 unless $hold->capture_time;
1209 my $copy = $hold->current_copy;
1210 unless( ref $copy ) {
1211 $copy = $e->retrieve_asset_copy($hold->current_copy)
1212 or return $e->event;
1215 return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
1217 if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
1219 my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
1220 return 4 unless $hs_wait_interval;
1222 # if a hold_shelf_status_delay interval is defined and start_time plus
1223 # the interval is greater than now, consider the hold to be in the virtual
1224 # "on its way to the holds shelf" status. Return 5.
1226 my $transit = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
1227 my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
1228 $start_time = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
1229 my $end_time = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
1231 return 5 if $end_time > DateTime->now;
1240 __PACKAGE__->register_method(
1241 method => "retrieve_hold_queue_stats",
1242 api_name => "open-ils.circ.hold.queue_stats.retrieve",
1244 desc => 'Returns summary data about the state of a hold',
1246 { desc => 'Authentication token', type => 'string'},
1247 { desc => 'Hold ID', type => 'number'},
1250 desc => q/Summary object with keys:
1251 total_holds : total holds in queue
1252 queue_position : current queue position
1253 potential_copies : number of potential copies for this hold
1254 estimated_wait : estimated wait time in days
1255 status : hold status
1256 -1 => error or unexpected state,
1257 1 => 'waiting for copy to become available',
1258 2 => 'waiting for copy capture',
1261 5 => 'hold-shelf-delay'
1268 sub retrieve_hold_queue_stats {
1269 my($self, $conn, $auth, $hold_id) = @_;
1270 my $e = new_editor(authtoken => $auth);
1271 return $e->event unless $e->checkauth;
1272 my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1273 if($e->requestor->id != $hold->usr) {
1274 return $e->event unless $e->allowed('VIEW_HOLD');
1276 return retrieve_hold_queue_status_impl($e, $hold);
1279 sub retrieve_hold_queue_status_impl {
1283 # The holds queue is defined as the distinct set of holds that share at
1284 # least one potential copy with the context hold, plus any holds that
1285 # share the same hold type and target. The latter part exists to
1286 # accomodate holds that currently have no potential copies
1287 my $q_holds = $e->json_query({
1289 # fetch cut_in_line and request_time since they're in the order_by
1290 # and we're asking for distinct values
1291 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1298 'field' => 'target_copy',
1299 'fkey' => 'target_copy'
1308 "field" => "cut_in_line",
1309 "transform" => "coalesce",
1311 "direction" => "desc"
1313 { "class" => "ahr", "field" => "request_time" }
1317 '+ahcm2' => { hold => $hold->id }
1321 if (!@$q_holds) { # none? maybe we don't have a map ...
1322 $q_holds = $e->json_query({
1323 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1328 "field" => "cut_in_line",
1329 "transform" => "coalesce",
1331 "direction" => "desc"
1333 { "class" => "ahr", "field" => "request_time" }
1336 hold_type => $hold->hold_type,
1337 target => $hold->target
1344 for my $h (@$q_holds) {
1345 last if $h->{id} == $hold->id;
1349 my $hold_data = $e->json_query({
1351 acp => [ {column => 'id', transform => 'count', aggregate => 1, alias => 'count'} ],
1352 ccm => [ {column =>'avg_wait_time'} ]
1358 ccm => {type => 'left'}
1363 where => {'+ahcm' => {hold => $hold->id} }
1366 my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1368 my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1369 my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1370 $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1371 $default_wait ||= '0 seconds';
1373 # Estimated wait time is the average wait time across the set
1374 # of potential copies, divided by the number of potential copies
1375 # times the queue position.
1377 my $combined_secs = 0;
1378 my $num_potentials = 0;
1380 for my $wait_data (@$hold_data) {
1381 my $count += $wait_data->{count};
1382 $combined_secs += $count *
1383 OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1384 $num_potentials += $count;
1387 my $estimated_wait = -1;
1389 if($num_potentials) {
1390 my $avg_wait = $combined_secs / $num_potentials;
1391 $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1392 $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1396 total_holds => scalar(@$q_holds),
1397 queue_position => $qpos,
1398 potential_copies => $num_potentials,
1399 status => _hold_status( $e, $hold ),
1400 estimated_wait => int($estimated_wait)
1405 sub fetch_open_hold_by_current_copy {
1408 my $hold = $apputils->simplereq(
1410 'open-ils.cstore.direct.action.hold_request.search.atomic',
1411 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1412 return $hold->[0] if ref($hold);
1416 sub fetch_related_holds {
1419 return $apputils->simplereq(
1421 'open-ils.cstore.direct.action.hold_request.search.atomic',
1422 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1426 __PACKAGE__->register_method(
1427 method => "hold_pull_list",
1428 api_name => "open-ils.circ.hold_pull_list.retrieve",
1430 desc => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1431 'The location is determined by the login session.',
1433 { desc => 'Limit (optional)', type => 'number'},
1434 { desc => 'Offset (optional)', type => 'number'},
1437 desc => 'reference to a list of holds, or event on failure',
1442 __PACKAGE__->register_method(
1443 method => "hold_pull_list",
1444 api_name => "open-ils.circ.hold_pull_list.id_list.retrieve",
1446 desc => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1447 'The location is determined by the login session.',
1449 { desc => 'Limit (optional)', type => 'number'},
1450 { desc => 'Offset (optional)', type => 'number'},
1453 desc => 'reference to a list of holds, or event on failure',
1458 __PACKAGE__->register_method(
1459 method => "hold_pull_list",
1460 api_name => "open-ils.circ.hold_pull_list.retrieve.count",
1462 desc => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1463 'The location is determined by the login session.',
1465 { desc => 'Limit (optional)', type => 'number'},
1466 { desc => 'Offset (optional)', type => 'number'},
1469 desc => 'Holds count (integer), or event on failure',
1476 sub hold_pull_list {
1477 my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1478 my( $reqr, $evt ) = $U->checkses($authtoken);
1479 return $evt if $evt;
1481 my $org = $reqr->ws_ou || $reqr->home_ou;
1482 # the perm locaiton shouldn't really matter here since holds
1483 # will exist all over and VIEW_HOLDS should be universal
1484 $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1485 return $evt if $evt;
1487 if($self->api_name =~ /count/) {
1489 my $count = $U->storagereq(
1490 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1491 $org, $limit, $offset );
1493 $logger->info("Grabbing pull list for org unit $org with $count items");
1496 } elsif( $self->api_name =~ /id_list/ ) {
1497 return $U->storagereq(
1498 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1499 $org, $limit, $offset );
1502 return $U->storagereq(
1503 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1504 $org, $limit, $offset );
1508 __PACKAGE__->register_method(
1509 method => "print_hold_pull_list",
1510 api_name => "open-ils.circ.hold_pull_list.print",
1512 desc => 'Returns an HTML-formatted holds pull list',
1514 { desc => 'Authtoken', type => 'string'},
1515 { desc => 'Org unit ID. Optional, defaults to workstation org unit', type => 'number'},
1518 desc => 'HTML string',
1524 sub print_hold_pull_list {
1525 my($self, $client, $auth, $org_id) = @_;
1527 my $e = new_editor(authtoken=>$auth);
1528 return $e->event unless $e->checkauth;
1530 $org_id = (defined $org_id) ? $org_id : $e->requestor->ws_ou;
1531 return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1533 my $hold_ids = $U->storagereq(
1534 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1537 return undef unless @$hold_ids;
1539 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1541 # Holds will /NOT/ be in order after this ...
1542 my $holds = $e->search_action_hold_request({id => $hold_ids}, {substream => 1});
1543 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1545 # ... so we must resort.
1546 my $hold_map = +{map { $_->id => $_ } @$holds};
1547 my $sorted_holds = [];
1548 push @$sorted_holds, $hold_map->{$_} foreach @$hold_ids;
1550 return $U->fire_object_event(
1551 undef, "ahr.format.pull_list", $sorted_holds,
1552 $org_id, undef, undef, $client
1557 __PACKAGE__->register_method(
1558 method => "print_hold_pull_list_stream",
1560 api_name => "open-ils.circ.hold_pull_list.print.stream",
1562 desc => 'Returns a stream of fleshed holds',
1564 { desc => 'Authtoken', type => 'string'},
1565 { 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)',
1570 desc => 'A stream of fleshed holds',
1576 sub print_hold_pull_list_stream {
1577 my($self, $client, $auth, $params) = @_;
1579 my $e = new_editor(authtoken=>$auth);
1580 return $e->die_event unless $e->checkauth;
1582 delete($$params{org_id}) unless (int($$params{org_id}));
1583 delete($$params{limit}) unless (int($$params{limit}));
1584 delete($$params{offset}) unless (int($$params{offset}));
1585 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1586 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1587 $$params{chunk_size} ||= 10;
1589 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1590 return $e->die_event unless $e->allowed('VIEW_HOLD', $$params{org_id });
1593 if ($$params{sort} && @{ $$params{sort} }) {
1594 for my $s (@{ $$params{sort} }) {
1595 if ($s eq 'acplo.position') {
1597 "class" => "acplo", "field" => "position",
1598 "transform" => "coalesce", "params" => [999]
1600 } elsif ($s eq 'prefix') {
1601 push @$sort, {"class" => "acnp", "field" => "label_sortkey"};
1602 } elsif ($s eq 'call_number') {
1603 push @$sort, {"class" => "acn", "field" => "label_sortkey"};
1604 } elsif ($s eq 'suffix') {
1605 push @$sort, {"class" => "acns", "field" => "label_sortkey"};
1606 } elsif ($s eq 'request_time') {
1607 push @$sort, {"class" => "ahr", "field" => "request_time"};
1611 push @$sort, {"class" => "ahr", "field" => "request_time"};
1614 my $holds_ids = $e->json_query(
1616 "select" => {"ahr" => ["id"]},
1621 "fkey" => "current_copy",
1623 "circ_lib" => $$params{org_id}, "status" => [0,7]
1628 "fkey" => "call_number",
1642 "fkey" => "circ_lib",
1645 "location" => {"=" => {"+acp" => "location"}}
1654 "capture_time" => undef,
1655 "cancel_time" => undef,
1657 {"expire_time" => undef },
1658 {"expire_time" => {">" => "now"}}
1662 (@$sort ? (order_by => $sort) : ()),
1663 ($$params{limit} ? (limit => $$params{limit}) : ()),
1664 ($$params{offset} ? (offset => $$params{offset}) : ())
1665 }, {"substream" => 1}
1666 ) or return $e->die_event;
1668 $logger->info("about to stream back " . scalar(@$holds_ids) . " holds");
1671 for my $hid (@$holds_ids) {
1672 push @chunk, $e->retrieve_action_hold_request([
1676 "ahr" => ["usr", "current_copy"],
1678 "acp" => ["location", "call_number", "parts"],
1679 "acn" => ["record","prefix","suffix"]
1684 if (@chunk >= $$params{chunk_size}) {
1685 $client->respond( \@chunk );
1689 $client->respond_complete( \@chunk ) if (@chunk);
1696 __PACKAGE__->register_method(
1697 method => 'fetch_hold_notify',
1698 api_name => 'open-ils.circ.hold_notification.retrieve_by_hold',
1701 Returns a list of hold notification objects based on hold id.
1702 @param authtoken The loggin session key
1703 @param holdid The id of the hold whose notifications we want to retrieve
1704 @return An array of hold notification objects, event on error.
1708 sub fetch_hold_notify {
1709 my( $self, $conn, $authtoken, $holdid ) = @_;
1710 my( $requestor, $evt ) = $U->checkses($authtoken);
1711 return $evt if $evt;
1712 my ($hold, $patron);
1713 ($hold, $evt) = $U->fetch_hold($holdid);
1714 return $evt if $evt;
1715 ($patron, $evt) = $U->fetch_user($hold->usr);
1716 return $evt if $evt;
1718 $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1719 return $evt if $evt;
1721 $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1722 return $U->cstorereq(
1723 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1727 __PACKAGE__->register_method(
1728 method => 'create_hold_notify',
1729 api_name => 'open-ils.circ.hold_notification.create',
1731 Creates a new hold notification object
1732 @param authtoken The login session key
1733 @param notification The hold notification object to create
1734 @return ID of the new object on success, Event on error
1738 sub create_hold_notify {
1739 my( $self, $conn, $auth, $note ) = @_;
1740 my $e = new_editor(authtoken=>$auth, xact=>1);
1741 return $e->die_event unless $e->checkauth;
1743 my $hold = $e->retrieve_action_hold_request($note->hold)
1744 or return $e->die_event;
1745 my $patron = $e->retrieve_actor_user($hold->usr)
1746 or return $e->die_event;
1748 return $e->die_event unless
1749 $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1751 $note->notify_staff($e->requestor->id);
1752 $e->create_action_hold_notification($note) or return $e->die_event;
1757 __PACKAGE__->register_method(
1758 method => 'create_hold_note',
1759 api_name => 'open-ils.circ.hold_note.create',
1761 Creates a new hold request note object
1762 @param authtoken The login session key
1763 @param note The hold note object to create
1764 @return ID of the new object on success, Event on error
1768 sub create_hold_note {
1769 my( $self, $conn, $auth, $note ) = @_;
1770 my $e = new_editor(authtoken=>$auth, xact=>1);
1771 return $e->die_event unless $e->checkauth;
1773 my $hold = $e->retrieve_action_hold_request($note->hold)
1774 or return $e->die_event;
1775 my $patron = $e->retrieve_actor_user($hold->usr)
1776 or return $e->die_event;
1778 return $e->die_event unless
1779 $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn. Probably want something more specific
1781 $e->create_action_hold_request_note($note) or return $e->die_event;
1786 __PACKAGE__->register_method(
1787 method => 'reset_hold',
1788 api_name => 'open-ils.circ.hold.reset',
1790 Un-captures and un-targets a hold, essentially returning
1791 it to the state it was in directly after it was placed,
1792 then attempts to re-target the hold
1793 @param authtoken The login session key
1794 @param holdid The id of the hold
1800 my( $self, $conn, $auth, $holdid ) = @_;
1802 my ($hold, $evt) = $U->fetch_hold($holdid);
1803 return $evt if $evt;
1804 ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1805 return $evt if $evt;
1806 $evt = _reset_hold($self, $reqr, $hold);
1807 return $evt if $evt;
1812 __PACKAGE__->register_method(
1813 method => 'reset_hold_batch',
1814 api_name => 'open-ils.circ.hold.reset.batch'
1817 sub reset_hold_batch {
1818 my($self, $conn, $auth, $hold_ids) = @_;
1820 my $e = new_editor(authtoken => $auth);
1821 return $e->event unless $e->checkauth;
1823 for my $hold_id ($hold_ids) {
1825 my $hold = $e->retrieve_action_hold_request(
1826 [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}])
1827 or return $e->event;
1829 next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1830 _reset_hold($self, $e->requestor, $hold);
1838 my ($self, $reqr, $hold) = @_;
1840 my $e = new_editor(xact =>1, requestor => $reqr);
1842 $logger->info("reseting hold ".$hold->id);
1844 my $hid = $hold->id;
1846 if( $hold->capture_time and $hold->current_copy ) {
1848 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1849 or return $e->die_event;
1851 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1852 $logger->info("setting copy to status 'reshelving' on hold retarget");
1853 $copy->status(OILS_COPY_STATUS_RESHELVING);
1854 $copy->editor($e->requestor->id);
1855 $copy->edit_date('now');
1856 $e->update_asset_copy($copy) or return $e->die_event;
1858 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1860 # We don't want the copy to remain "in transit"
1861 $copy->status(OILS_COPY_STATUS_RESHELVING);
1862 $logger->warn("! reseting hold [$hid] that is in transit");
1863 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1866 my $trans = $e->retrieve_action_transit_copy($transid);
1868 $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1869 my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1);
1870 $logger->info("Transit abort completed with result $evt");
1871 unless ("$evt" eq 1) {
1880 $hold->clear_capture_time;
1881 $hold->clear_current_copy;
1882 $hold->clear_shelf_time;
1883 $hold->clear_shelf_expire_time;
1884 $hold->clear_current_shelf_lib;
1886 $e->update_action_hold_request($hold) or return $e->die_event;
1890 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1896 __PACKAGE__->register_method(
1897 method => 'fetch_open_title_holds',
1898 api_name => 'open-ils.circ.open_holds.retrieve',
1900 Returns a list ids of un-fulfilled holds for a given title id
1901 @param authtoken The login session key
1902 @param id the id of the item whose holds we want to retrieve
1903 @param type The hold type - M, T, I, V, C, F, R
1907 sub fetch_open_title_holds {
1908 my( $self, $conn, $auth, $id, $type, $org ) = @_;
1909 my $e = new_editor( authtoken => $auth );
1910 return $e->event unless $e->checkauth;
1913 $org ||= $e->requestor->ws_ou;
1915 # return $e->search_action_hold_request(
1916 # { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1918 # XXX make me return IDs in the future ^--
1919 my $holds = $e->search_action_hold_request(
1922 cancel_time => undef,
1924 fulfillment_time => undef
1928 flesh_hold_transits($holds);
1933 sub flesh_hold_transits {
1935 for my $hold ( @$holds ) {
1937 $apputils->simplereq(
1939 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1940 { hold => $hold->id },
1941 { order_by => { ahtc => 'id desc' }, limit => 1 }
1947 sub flesh_hold_notices {
1948 my( $holds, $e ) = @_;
1949 $e ||= new_editor();
1951 for my $hold (@$holds) {
1952 my $notices = $e->search_action_hold_notification(
1954 { hold => $hold->id },
1955 { order_by => { anh => 'notify_time desc' } },
1960 $hold->notify_count(scalar(@$notices));
1962 my $n = $e->retrieve_action_hold_notification($$notices[0])
1963 or return $e->event;
1964 $hold->notify_time($n->notify_time);
1970 __PACKAGE__->register_method(
1971 method => 'fetch_captured_holds',
1972 api_name => 'open-ils.circ.captured_holds.on_shelf.retrieve',
1976 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
1977 @param authtoken The login session key
1978 @param org The org id of the location in question
1979 @param match_copy A specific copy to limit to
1983 __PACKAGE__->register_method(
1984 method => 'fetch_captured_holds',
1985 api_name => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
1989 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
1990 @param authtoken The login session key
1991 @param org The org id of the location in question
1992 @param match_copy A specific copy to limit to
1996 __PACKAGE__->register_method(
1997 method => 'fetch_captured_holds',
1998 api_name => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
2002 Returns list ids of shelf-expired un-fulfilled holds for a given title id
2003 @param authtoken The login session key
2004 @param org The org id of the location in question
2005 @param match_copy A specific copy to limit to
2010 sub fetch_captured_holds {
2011 my( $self, $conn, $auth, $org, $match_copy ) = @_;
2013 my $e = new_editor(authtoken => $auth);
2014 return $e->die_event unless $e->checkauth;
2015 return $e->die_event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
2017 $org ||= $e->requestor->ws_ou;
2019 my $current_copy = { '!=' => undef };
2020 $current_copy = { '=' => $match_copy } if $match_copy;
2023 select => { alhr => ['id'] },
2028 fkey => 'current_copy'
2033 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
2035 capture_time => { "!=" => undef },
2036 current_copy => $current_copy,
2037 fulfillment_time => undef,
2038 current_shelf_lib => $org
2042 if($self->api_name =~ /expired/) {
2043 $query->{'where'}->{'+alhr'}->{'-or'} = {
2044 shelf_expire_time => { '<' => 'now'},
2045 cancel_time => { '!=' => undef },
2048 my $hold_ids = $e->json_query( $query );
2050 for my $hold_id (@$hold_ids) {
2051 if($self->api_name =~ /id_list/) {
2052 $conn->respond($hold_id->{id});
2056 $e->retrieve_action_hold_request([
2060 flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
2061 order_by => {anh => 'notify_time desc'}
2071 __PACKAGE__->register_method(
2072 method => "print_expired_holds_stream",
2073 api_name => "open-ils.circ.captured_holds.expired.print.stream",
2077 sub print_expired_holds_stream {
2078 my ($self, $client, $auth, $params) = @_;
2080 # No need to check specific permissions: we're going to call another method
2081 # that will do that.
2082 my $e = new_editor("authtoken" => $auth);
2083 return $e->die_event unless $e->checkauth;
2085 delete($$params{org_id}) unless (int($$params{org_id}));
2086 delete($$params{limit}) unless (int($$params{limit}));
2087 delete($$params{offset}) unless (int($$params{offset}));
2088 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
2089 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
2090 $$params{chunk_size} ||= 10;
2092 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
2094 my @hold_ids = $self->method_lookup(
2095 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
2096 )->run($auth, $params->{"org_id"});
2101 } elsif (defined $U->event_code($hold_ids[0])) {
2103 return $hold_ids[0];
2106 $logger->info("about to stream back up to " . scalar(@hold_ids) . " expired holds");
2109 my @hid_chunk = splice @hold_ids, 0, $params->{"chunk_size"};
2111 my $result_chunk = $e->json_query({
2113 "acp" => ["barcode"],
2115 first_given_name second_given_name family_name alias
2124 "field" => "id", "fkey" => "current_copy",
2127 "field" => "id", "fkey" => "call_number",
2130 "field" => "id", "fkey" => "record"
2134 "acpl" => {"field" => "id", "fkey" => "location"}
2137 "au" => {"field" => "id", "fkey" => "usr"}
2140 "where" => {"+ahr" => {"id" => \@hid_chunk}}
2141 }) or return $e->die_event;
2142 $client->respond($result_chunk);
2149 __PACKAGE__->register_method(
2150 method => "check_title_hold_batch",
2151 api_name => "open-ils.circ.title_hold.is_possible.batch",
2154 desc => '@see open-ils.circ.title_hold.is_possible.batch',
2156 { desc => 'Authentication token', type => 'string'},
2157 { desc => 'Array of Hash of named parameters', type => 'array'},
2160 desc => 'Array of response objects',
2166 sub check_title_hold_batch {
2167 my($self, $client, $authtoken, $param_list, $oargs) = @_;
2168 foreach (@$param_list) {
2169 my ($res) = $self->method_lookup('open-ils.circ.title_hold.is_possible')->run($authtoken, $_, $oargs);
2170 $client->respond($res);
2176 __PACKAGE__->register_method(
2177 method => "check_title_hold",
2178 api_name => "open-ils.circ.title_hold.is_possible",
2180 desc => 'Determines if a hold were to be placed by a given user, ' .
2181 'whether or not said hold would have any potential copies to fulfill it.' .
2182 'The named paramaters of the second argument include: ' .
2183 'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
2184 'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' ,
2186 { desc => 'Authentication token', type => 'string'},
2187 { desc => 'Hash of named parameters', type => 'object'},
2190 desc => 'List of new message IDs (empty if none)',
2196 =head3 check_title_hold (token, hash)
2198 The named fields in the hash are:
2200 patronid - ID of the hold recipient (required)
2201 depth - hold range depth (default 0)
2202 pickup_lib - destination for hold, fallback value for selection_ou
2203 selection_ou - ID of org_unit establishing hard and soft hold boundary settings
2204 issuanceid - ID of the issuance to be held, required for Issuance level hold
2205 partid - ID of the monograph part to be held, required for monograph part level hold
2206 titleid - ID (BRN) of the title to be held, required for Title level hold
2207 volume_id - required for Volume level hold
2208 copy_id - required for Copy level hold
2209 mrid - required for Meta-record level hold
2210 hold_type - T, C (or R or F), I, V or M for Title, Copy, Issuance, Volume or Meta-record (default "T")
2212 All key/value pairs are passed on to do_possibility_checks.
2216 # FIXME: better params checking. what other params are required, if any?
2217 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
2218 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still
2219 # used in conditionals, where it may be undefined, causing a warning.
2220 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
2222 sub check_title_hold {
2223 my( $self, $client, $authtoken, $params, $oargs ) = @_;
2224 my $e = new_editor(authtoken=>$authtoken);
2225 return $e->event unless $e->checkauth;
2226 $oargs = {} unless defined $oargs;
2228 if($oargs->{events}) {
2229 @{$oargs->{events}} = grep { $e->allowed($_ . '.override', $e->requestor->ws_ou); } @{$oargs->{events}};
2232 my %params = %$params;
2233 my $depth = $params{depth} || 0;
2234 my $selection_ou = $params{selection_ou} || $params{pickup_lib};
2236 my $patron = $e->retrieve_actor_user($params{patronid})
2237 or return $e->event;
2239 if( $e->requestor->id ne $patron->id ) {
2240 return $e->event unless
2241 $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
2244 return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
2246 my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
2247 or return $e->event;
2249 my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
2250 my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
2253 my $return_depth = $hard_boundary; # default depth to return on success
2254 if(defined $soft_boundary and $depth < $soft_boundary) {
2255 # work up the tree and as soon as we find a potential copy, use that depth
2256 # also, make sure we don't go past the hard boundary if it exists
2258 # our min boundary is the greater of user-specified boundary or hard boundary
2259 my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?
2260 $hard_boundary : $depth;
2262 my $depth = $soft_boundary;
2263 while($depth >= $min_depth) {
2264 $logger->info("performing hold possibility check with soft boundary $depth");
2265 @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params, $oargs);
2267 $return_depth = $depth;
2272 } elsif(defined $hard_boundary and $depth < $hard_boundary) {
2273 # there is no soft boundary, enforce the hard boundary if it exists
2274 $logger->info("performing hold possibility check with hard boundary $hard_boundary");
2275 @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params, $oargs);
2277 # no boundaries defined, fall back to user specifed boundary or no boundary
2278 $logger->info("performing hold possibility check with no boundary");
2279 @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params, $oargs);
2282 my $place_unfillable = 0;
2283 $place_unfillable = 1 if $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
2288 "depth" => $return_depth,
2289 "local_avail" => $status[1]
2291 } elsif ($status[2]) {
2292 my $n = scalar @{$status[2]};
2293 return {"success" => 0, "last_event" => $status[2]->[$n - 1], "age_protected_copy" => $status[3], "place_unfillable" => $place_unfillable};
2295 return {"success" => 0, "age_protected_copy" => $status[3], "place_unfillable" => $place_unfillable};
2301 sub do_possibility_checks {
2302 my($e, $patron, $request_lib, $depth, %params, $oargs) = @_;
2304 my $issuanceid = $params{issuanceid} || "";
2305 my $partid = $params{partid} || "";
2306 my $titleid = $params{titleid} || "";
2307 my $volid = $params{volume_id};
2308 my $copyid = $params{copy_id};
2309 my $mrid = $params{mrid} || "";
2310 my $pickup_lib = $params{pickup_lib};
2311 my $hold_type = $params{hold_type} || 'T';
2312 my $selection_ou = $params{selection_ou} || $pickup_lib;
2313 my $holdable_formats = $params{holdable_formats};
2320 if( $hold_type eq OILS_HOLD_TYPE_FORCE || $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_COPY ) {
2322 return $e->event unless $copy = $e->retrieve_asset_copy($copyid);
2323 return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
2324 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2326 return (1, 1, []) if( $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_FORCE);
2327 return verify_copy_for_hold(
2328 $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib, $oargs
2331 } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2333 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
2334 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2336 return _check_volume_hold_is_possible(
2337 $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2340 } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
2342 return _check_title_hold_is_possible(
2343 $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2346 } elsif( $hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2348 return _check_issuance_hold_is_possible(
2349 $issuanceid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2352 } elsif( $hold_type eq OILS_HOLD_TYPE_MONOPART ) {
2354 return _check_monopart_hold_is_possible(
2355 $partid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2358 } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2360 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
2361 my @recs = map { $_->source } @$maps;
2363 for my $rec (@recs) {
2364 @status = _check_title_hold_is_possible(
2365 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $holdable_formats, $oargs
2371 # else { Unrecognized hold_type ! } # FIXME: return error? or 0?
2375 sub create_ranged_org_filter {
2376 my($e, $selection_ou, $depth) = @_;
2378 # find the orgs from which this hold may be fulfilled,
2379 # based on the selection_ou and depth
2381 my $top_org = $e->search_actor_org_unit([
2382 {parent_ou => undef},
2383 {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
2386 return () if $depth == $top_org->ou_type->depth;
2388 my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
2389 %org_filter = (circ_lib => []);
2390 push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
2392 $logger->info("hold org filter at depth $depth and selection_ou ".
2393 "$selection_ou created list of @{$org_filter{circ_lib}}");
2399 sub _check_title_hold_is_possible {
2400 my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $holdable_formats, $oargs ) = @_;
2402 my ($types, $formats, $lang);
2403 if (defined($holdable_formats)) {
2404 ($types, $formats, $lang) = split '-', $holdable_formats;
2407 my $e = new_editor();
2408 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2410 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2411 my $copies = $e->json_query(
2413 select => { acp => ['id', 'circ_lib'] },
2418 fkey => 'call_number',
2422 filter => { id => $titleid },
2430 ( $types ? (item_type => [split '', $types]) : () ),
2431 ( $formats ? (item_form => [split '', $formats]) : () ),
2432 ( $lang ? (item_lang => $lang) : () )
2437 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2438 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' },
2439 acpm => { field => 'target_copy', type => 'left' } # ignore part-linked copies
2443 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter },
2444 '+acpm' => { target_copy => undef } # ignore part-linked copies
2449 $logger->info("title possible found ".scalar(@$copies)." potential copies");
2453 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2454 "payload" => {"fail_part" => "no_ultimate_items"}
2459 # -----------------------------------------------------------------------
2460 # sort the copies into buckets based on their circ_lib proximity to
2461 # the patron's home_ou.
2462 # -----------------------------------------------------------------------
2464 my $home_org = $patron->home_ou;
2465 my $req_org = $request_lib->id;
2467 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2469 $prox_cache{$home_org} =
2470 $e->search_actor_org_unit_proximity({from_org => $home_org})
2471 unless $prox_cache{$home_org};
2472 my $home_prox = $prox_cache{$home_org};
2475 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2476 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2478 my @keys = sort { $a <=> $b } keys %buckets;
2481 if( $home_org ne $req_org ) {
2482 # -----------------------------------------------------------------------
2483 # shove the copies close to the request_lib into the primary buckets
2484 # directly before the farthest away copies. That way, they are not
2485 # given priority, but they are checked before the farthest copies.
2486 # -----------------------------------------------------------------------
2487 $prox_cache{$req_org} =
2488 $e->search_actor_org_unit_proximity({from_org => $req_org})
2489 unless $prox_cache{$req_org};
2490 my $req_prox = $prox_cache{$req_org};
2493 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2494 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2496 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2497 my $new_key = $highest_key - 0.5; # right before the farthest prox
2498 my @keys2 = sort { $a <=> $b } keys %buckets2;
2499 for my $key (@keys2) {
2500 last if $key >= $highest_key;
2501 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2505 @keys = sort { $a <=> $b } keys %buckets;
2510 my $age_protect_only = 0;
2511 OUTER: for my $key (@keys) {
2512 my @cps = @{$buckets{$key}};
2514 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2516 for my $copyid (@cps) {
2518 next if $seen{$copyid};
2519 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2520 my $copy = $e->retrieve_asset_copy($copyid);
2521 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2523 unless($title) { # grab the title if we don't already have it
2524 my $vol = $e->retrieve_asset_call_number(
2525 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2526 $title = $vol->record;
2529 @status = verify_copy_for_hold(
2530 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2532 $age_protect_only ||= $status[3];
2533 last OUTER if $status[0];
2537 $status[3] = $age_protect_only;
2541 sub _check_issuance_hold_is_possible {
2542 my( $issuanceid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2544 my $e = new_editor();
2545 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2547 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2548 my $copies = $e->json_query(
2550 select => { acp => ['id', 'circ_lib'] },
2556 filter => { issuance => $issuanceid }
2558 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2559 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2563 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2569 $logger->info("issuance possible found ".scalar(@$copies)." potential copies");
2573 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2574 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2579 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2580 "payload" => {"fail_part" => "no_ultimate_items"}
2588 # -----------------------------------------------------------------------
2589 # sort the copies into buckets based on their circ_lib proximity to
2590 # the patron's home_ou.
2591 # -----------------------------------------------------------------------
2593 my $home_org = $patron->home_ou;
2594 my $req_org = $request_lib->id;
2596 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2598 $prox_cache{$home_org} =
2599 $e->search_actor_org_unit_proximity({from_org => $home_org})
2600 unless $prox_cache{$home_org};
2601 my $home_prox = $prox_cache{$home_org};
2604 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2605 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2607 my @keys = sort { $a <=> $b } keys %buckets;
2610 if( $home_org ne $req_org ) {
2611 # -----------------------------------------------------------------------
2612 # shove the copies close to the request_lib into the primary buckets
2613 # directly before the farthest away copies. That way, they are not
2614 # given priority, but they are checked before the farthest copies.
2615 # -----------------------------------------------------------------------
2616 $prox_cache{$req_org} =
2617 $e->search_actor_org_unit_proximity({from_org => $req_org})
2618 unless $prox_cache{$req_org};
2619 my $req_prox = $prox_cache{$req_org};
2622 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2623 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2625 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2626 my $new_key = $highest_key - 0.5; # right before the farthest prox
2627 my @keys2 = sort { $a <=> $b } keys %buckets2;
2628 for my $key (@keys2) {
2629 last if $key >= $highest_key;
2630 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2634 @keys = sort { $a <=> $b } keys %buckets;
2639 my $age_protect_only = 0;
2640 OUTER: for my $key (@keys) {
2641 my @cps = @{$buckets{$key}};
2643 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2645 for my $copyid (@cps) {
2647 next if $seen{$copyid};
2648 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2649 my $copy = $e->retrieve_asset_copy($copyid);
2650 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2652 unless($title) { # grab the title if we don't already have it
2653 my $vol = $e->retrieve_asset_call_number(
2654 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2655 $title = $vol->record;
2658 @status = verify_copy_for_hold(
2659 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2661 $age_protect_only ||= $status[3];
2662 last OUTER if $status[0];
2667 if (!defined($empty_ok)) {
2668 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2669 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2672 return (1,0) if ($empty_ok);
2674 $status[3] = $age_protect_only;
2678 sub _check_monopart_hold_is_possible {
2679 my( $partid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2681 my $e = new_editor();
2682 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2684 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2685 my $copies = $e->json_query(
2687 select => { acp => ['id', 'circ_lib'] },
2691 field => 'target_copy',
2693 filter => { part => $partid }
2695 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2696 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2700 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2706 $logger->info("monopart possible found ".scalar(@$copies)." potential copies");
2710 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2711 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2716 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2717 "payload" => {"fail_part" => "no_ultimate_items"}
2725 # -----------------------------------------------------------------------
2726 # sort the copies into buckets based on their circ_lib proximity to
2727 # the patron's home_ou.
2728 # -----------------------------------------------------------------------
2730 my $home_org = $patron->home_ou;
2731 my $req_org = $request_lib->id;
2733 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2735 $prox_cache{$home_org} =
2736 $e->search_actor_org_unit_proximity({from_org => $home_org})
2737 unless $prox_cache{$home_org};
2738 my $home_prox = $prox_cache{$home_org};
2741 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2742 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2744 my @keys = sort { $a <=> $b } keys %buckets;
2747 if( $home_org ne $req_org ) {
2748 # -----------------------------------------------------------------------
2749 # shove the copies close to the request_lib into the primary buckets
2750 # directly before the farthest away copies. That way, they are not
2751 # given priority, but they are checked before the farthest copies.
2752 # -----------------------------------------------------------------------
2753 $prox_cache{$req_org} =
2754 $e->search_actor_org_unit_proximity({from_org => $req_org})
2755 unless $prox_cache{$req_org};
2756 my $req_prox = $prox_cache{$req_org};
2759 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2760 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2762 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2763 my $new_key = $highest_key - 0.5; # right before the farthest prox
2764 my @keys2 = sort { $a <=> $b } keys %buckets2;
2765 for my $key (@keys2) {
2766 last if $key >= $highest_key;
2767 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2771 @keys = sort { $a <=> $b } keys %buckets;
2776 my $age_protect_only = 0;
2777 OUTER: for my $key (@keys) {
2778 my @cps = @{$buckets{$key}};
2780 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2782 for my $copyid (@cps) {
2784 next if $seen{$copyid};
2785 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2786 my $copy = $e->retrieve_asset_copy($copyid);
2787 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2789 unless($title) { # grab the title if we don't already have it
2790 my $vol = $e->retrieve_asset_call_number(
2791 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2792 $title = $vol->record;
2795 @status = verify_copy_for_hold(
2796 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2798 $age_protect_only ||= $status[3];
2799 last OUTER if $status[0];
2804 if (!defined($empty_ok)) {
2805 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2806 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2809 return (1,0) if ($empty_ok);
2811 $status[3] = $age_protect_only;
2816 sub _check_volume_hold_is_possible {
2817 my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2818 my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
2819 my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
2820 $logger->info("checking possibility of volume hold for volume ".$vol->id);
2822 my $filter_copies = [];
2823 for my $copy (@$copies) {
2824 # ignore part-mapped copies for regular volume level holds
2825 push(@$filter_copies, $copy) unless
2826 new_editor->search_asset_copy_part_map({target_copy => $copy->id})->[0];
2828 $copies = $filter_copies;
2833 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2834 "payload" => {"fail_part" => "no_ultimate_items"}
2840 my $age_protect_only = 0;
2841 for my $copy ( @$copies ) {
2842 @status = verify_copy_for_hold(
2843 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs );
2844 $age_protect_only ||= $status[3];
2847 $status[3] = $age_protect_only;
2853 sub verify_copy_for_hold {
2854 my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs ) = @_;
2855 $oargs = {} unless defined $oargs;
2856 $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
2857 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2858 { patron => $patron,
2859 requestor => $requestor,
2862 title_descriptor => $title->fixed_fields, # this is fleshed into the title object
2863 pickup_lib => $pickup_lib,
2864 request_lib => $request_lib,
2866 show_event_list => 1
2871 my $permit_anyway = 0;
2872 foreach my $permit_event (@$permitted) {
2873 if (grep { $_ eq $permit_event->{textcode} } @{$oargs->{events}}) {
2878 $permitted = [] if $permit_anyway;
2880 my $age_protect_only = 0;
2881 if (@$permitted == 1 && @$permitted[0]->{textcode} eq 'ITEM_AGE_PROTECTED') {
2882 $age_protect_only = 1;
2886 (not scalar @$permitted), # true if permitted is an empty arrayref
2887 ( # XXX This test is of very dubious value; someone should figure
2888 # out what if anything is checking this value
2889 ($copy->circ_lib == $pickup_lib) and
2890 ($copy->status == OILS_COPY_STATUS_AVAILABLE)
2899 sub find_nearest_permitted_hold {
2902 my $editor = shift; # CStoreEditor object
2903 my $copy = shift; # copy to target
2904 my $user = shift; # staff
2905 my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
2907 my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
2909 my $bc = $copy->barcode;
2911 # find any existing holds that already target this copy
2912 my $old_holds = $editor->search_action_hold_request(
2913 { current_copy => $copy->id,
2914 cancel_time => undef,
2915 capture_time => undef
2919 my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
2921 $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
2922 " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
2924 my $fifo = $U->ou_ancestor_setting_value($user->ws_ou, 'circ.holds_fifo');
2926 # search for what should be the best holds for this copy to fulfill
2927 my $best_holds = $U->storagereq(
2928 "open-ils.storage.action.hold_request.nearest_hold.atomic",
2929 $user->ws_ou, $copy->id, 100, $hold_stall_interval, $fifo );
2931 # Add any pre-targeted holds to the list too? Unless they are already there, anyway.
2933 for my $holdid (@$old_holds) {
2934 next unless $holdid;
2935 push(@$best_holds, $holdid) unless ( grep { ''.$holdid eq ''.$_ } @$best_holds );
2939 unless(@$best_holds) {
2940 $logger->info("circulator: no suitable holds found for copy $bc");
2941 return (undef, $evt);
2947 # for each potential hold, we have to run the permit script
2948 # to make sure the hold is actually permitted.
2951 for my $holdid (@$best_holds) {
2952 next unless $holdid;
2953 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
2955 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
2956 my $reqr = $reqr_cache{$hold->requestor} || $editor->retrieve_actor_user($hold->requestor);
2957 my $rlib = $org_cache{$hold->request_lib} || $editor->retrieve_actor_org_unit($hold->request_lib);
2959 $reqr_cache{$hold->requestor} = $reqr;
2960 $org_cache{$hold->request_lib} = $rlib;
2962 # see if this hold is permitted
2963 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2964 { patron_id => $hold->usr,
2967 pickup_lib => $hold->pickup_lib,
2968 request_lib => $rlib,
2980 unless( $best_hold ) { # no "good" permitted holds were found
2982 $logger->info("circulator: no suitable holds found for copy $bc");
2983 return (undef, $evt);
2986 $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
2988 # indicate a permitted hold was found
2989 return $best_hold if $check_only;
2991 # we've found a permitted hold. we need to "grab" the copy
2992 # to prevent re-targeted holds (next part) from re-grabbing the copy
2993 $best_hold->current_copy($copy->id);
2994 $editor->update_action_hold_request($best_hold)
2995 or return (undef, $editor->event);
3000 # re-target any other holds that already target this copy
3001 for my $old_hold (@$old_holds) {
3002 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
3003 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
3004 $old_hold->id." after a better hold [".$best_hold->id."] was found");
3005 $old_hold->clear_current_copy;
3006 $old_hold->clear_prev_check_time;
3007 $editor->update_action_hold_request($old_hold)
3008 or return (undef, $editor->event);
3009 push(@retarget, $old_hold->id);
3012 return ($best_hold, undef, (@retarget) ? \@retarget : undef);
3020 __PACKAGE__->register_method(
3021 method => 'all_rec_holds',
3022 api_name => 'open-ils.circ.holds.retrieve_all_from_title',
3026 my( $self, $conn, $auth, $title_id, $args ) = @_;
3028 my $e = new_editor(authtoken=>$auth);
3029 $e->checkauth or return $e->event;
3030 $e->allowed('VIEW_HOLD') or return $e->event;
3033 $args->{fulfillment_time} = undef; # we don't want to see old fulfilled holds
3034 $args->{cancel_time} = undef;
3036 my $resp = { volume_holds => [], copy_holds => [], recall_holds => [], force_holds => [], metarecord_holds => [], part_holds => [], issuance_holds => [] };
3038 my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
3040 $resp->{metarecord_holds} = $e->search_action_hold_request(
3041 { hold_type => OILS_HOLD_TYPE_METARECORD,
3042 target => $mr_map->metarecord,
3048 $resp->{title_holds} = $e->search_action_hold_request(
3050 hold_type => OILS_HOLD_TYPE_TITLE,
3051 target => $title_id,
3055 my $parts = $e->search_biblio_monograph_part(
3061 $resp->{part_holds} = $e->search_action_hold_request(
3063 hold_type => OILS_HOLD_TYPE_MONOPART,
3069 my $subs = $e->search_serial_subscription(
3070 { record_entry => $title_id }, {idlist=>1});
3073 my $issuances = $e->search_serial_issuance(
3074 {subscription => $subs}, {idlist=>1}
3078 $resp->{issuance_holds} = $e->search_action_hold_request(
3080 hold_type => OILS_HOLD_TYPE_ISSUANCE,
3081 target => $issuances,
3088 my $vols = $e->search_asset_call_number(
3089 { record => $title_id, deleted => 'f' }, {idlist=>1});
3091 return $resp unless @$vols;
3093 $resp->{volume_holds} = $e->search_action_hold_request(
3095 hold_type => OILS_HOLD_TYPE_VOLUME,
3100 my $copies = $e->search_asset_copy(
3101 { call_number => $vols, deleted => 'f' }, {idlist=>1});
3103 return $resp unless @$copies;
3105 $resp->{copy_holds} = $e->search_action_hold_request(
3107 hold_type => OILS_HOLD_TYPE_COPY,
3112 $resp->{recall_holds} = $e->search_action_hold_request(
3114 hold_type => OILS_HOLD_TYPE_RECALL,
3119 $resp->{force_holds} = $e->search_action_hold_request(
3121 hold_type => OILS_HOLD_TYPE_FORCE,
3133 __PACKAGE__->register_method(
3134 method => 'uber_hold',
3136 api_name => 'open-ils.circ.hold.details.retrieve'
3140 my($self, $client, $auth, $hold_id, $args) = @_;
3141 my $e = new_editor(authtoken=>$auth);
3142 $e->checkauth or return $e->event;
3143 return uber_hold_impl($e, $hold_id, $args);
3146 __PACKAGE__->register_method(
3147 method => 'batch_uber_hold',
3150 api_name => 'open-ils.circ.hold.details.batch.retrieve'
3153 sub batch_uber_hold {
3154 my($self, $client, $auth, $hold_ids, $args) = @_;
3155 my $e = new_editor(authtoken=>$auth);
3156 $e->checkauth or return $e->event;
3157 $client->respond(uber_hold_impl($e, $_, $args)) for @$hold_ids;
3161 sub uber_hold_impl {
3162 my($e, $hold_id, $args) = @_;
3165 my $hold = $e->retrieve_action_hold_request(
3170 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
3173 ) or return $e->event;
3175 if($hold->usr->id ne $e->requestor->id) {
3176 # A user is allowed to see his/her own holds
3177 $e->allowed('VIEW_HOLD') or return $e->event;
3178 $hold->notes( # filter out any non-staff ("private") notes
3179 [ grep { !$U->is_true($_->staff) } @{$hold->notes} ] );
3182 # caller is asking for own hold, but may not have permission to view staff notes
3183 unless($e->allowed('VIEW_HOLD')) {
3184 $hold->notes( # filter out any staff notes
3185 [ grep { $U->is_true($_->staff) } @{$hold->notes} ] );
3189 my $user = $hold->usr;
3190 $hold->usr($user->id);
3193 my( $mvr, $volume, $copy, $issuance, $part, $bre ) = find_hold_mvr($e, $hold, $args->{suppress_mvr});
3195 flesh_hold_notices([$hold], $e) unless $args->{suppress_notices};
3196 flesh_hold_transits([$hold]) unless $args->{suppress_transits};
3198 my $details = retrieve_hold_queue_status_impl($e, $hold);
3203 ($copy ? (copy => $copy) : ()),
3204 ($volume ? (volume => $volume) : ()),
3205 ($issuance ? (issuance => $issuance) : ()),
3206 ($part ? (part => $part) : ()),
3207 ($args->{include_bre} ? (bre => $bre) : ()),
3208 ($args->{suppress_mvr} ? () : (mvr => $mvr)),
3212 unless($args->{suppress_patron_details}) {
3213 my $card = $e->retrieve_actor_card($user->card) or return $e->event;
3214 $resp->{patron_first} = $user->first_given_name,
3215 $resp->{patron_last} = $user->family_name,
3216 $resp->{patron_barcode} = $card->barcode,
3217 $resp->{patron_alias} = $user->alias,
3225 # -----------------------------------------------------
3226 # Returns the MVR object that represents what the
3228 # -----------------------------------------------------
3230 my( $e, $hold, $no_mvr ) = @_;
3238 if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
3239 my $mr = $e->retrieve_metabib_metarecord($hold->target)
3240 or return $e->event;
3241 $tid = $mr->master_record;
3243 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
3244 $tid = $hold->target;
3246 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
3247 $volume = $e->retrieve_asset_call_number($hold->target)
3248 or return $e->event;
3249 $tid = $volume->record;
3251 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
3252 $issuance = $e->retrieve_serial_issuance([
3254 {flesh => 1, flesh_fields => {siss => [ qw/subscription/ ]}}
3255 ]) or return $e->event;
3257 $tid = $issuance->subscription->record_entry;
3259 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_MONOPART ) {
3260 $part = $e->retrieve_biblio_monograph_part([
3262 ]) or return $e->event;
3264 $tid = $part->record;
3266 } 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 ) {
3267 $copy = $e->retrieve_asset_copy([
3269 {flesh => 1, flesh_fields => {acp => ['call_number']}}
3270 ]) or return $e->event;
3272 $volume = $copy->call_number;
3273 $tid = $volume->record;
3276 if(!$copy and ref $hold->current_copy ) {
3277 $copy = $hold->current_copy;
3278 $hold->current_copy($copy->id);
3281 if(!$volume and $copy) {
3282 $volume = $e->retrieve_asset_call_number($copy->call_number);
3285 # TODO return metarcord mvr for M holds
3286 my $title = $e->retrieve_biblio_record_entry($tid);
3287 return ( ($no_mvr) ? undef : $U->record_to_mvr($title), $volume, $copy, $issuance, $part, $title );
3290 __PACKAGE__->register_method(
3291 method => 'clear_shelf_cache',
3292 api_name => 'open-ils.circ.hold.clear_shelf.get_cache',
3296 Returns the holds processed with the given cache key
3301 sub clear_shelf_cache {
3302 my($self, $client, $auth, $cache_key, $chunk_size) = @_;
3303 my $e = new_editor(authtoken => $auth, xact => 1);
3304 return $e->die_event unless $e->checkauth and $e->allowed('VIEW_HOLD');
3307 my $hold_data = OpenSRF::Utils::Cache->new('global')->get_cache($cache_key);
3310 $logger->info("no hold data found in cache"); # XXX TODO return event
3316 foreach (keys %$hold_data) {
3317 $maximum += scalar(@{ $hold_data->{$_} });
3319 $client->respond({"maximum" => $maximum, "progress" => 0});
3321 for my $action (sort keys %$hold_data) {
3322 while (@{$hold_data->{$action}}) {
3323 my @hid_chunk = splice @{$hold_data->{$action}}, 0, $chunk_size;
3325 my $result_chunk = $e->json_query({
3327 "acp" => ["barcode"],
3329 first_given_name second_given_name family_name alias
3332 "acnp" => [{column => "label", alias => "prefix"}],
3333 "acns" => [{column => "label", alias => "suffix"}],
3341 "field" => "id", "fkey" => "current_copy",
3344 "field" => "id", "fkey" => "call_number",
3347 "field" => "id", "fkey" => "record"
3350 "field" => "id", "fkey" => "prefix"
3353 "field" => "id", "fkey" => "suffix"
3357 "acpl" => {"field" => "id", "fkey" => "location"}
3360 "au" => {"field" => "id", "fkey" => "usr"}
3363 "where" => {"+ahr" => {"id" => \@hid_chunk}}
3364 }, {"substream" => 1}) or return $e->die_event;
3368 +{"action" => $action, "hold_details" => $_}
3379 __PACKAGE__->register_method(
3380 method => 'clear_shelf_process',
3382 api_name => 'open-ils.circ.hold.clear_shelf.process',
3385 1. Find all holds that have expired on the holds shelf
3387 3. If a clear-shelf status is configured, put targeted copies into this status
3388 4. Divide copies into 3 groups: items to transit, items to reshelve, and items
3389 that are needed for holds. No subsequent action is taken on the holds
3390 or items after grouping.
3395 sub clear_shelf_process {
3396 my($self, $client, $auth, $org_id, $match_copy) = @_;
3398 my $e = new_editor(authtoken=>$auth, xact => 1);
3399 $e->checkauth or return $e->die_event;
3400 my $cache = OpenSRF::Utils::Cache->new('global');
3402 $org_id ||= $e->requestor->ws_ou;
3403 $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
3405 my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
3407 my @hold_ids = $self->method_lookup(
3408 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
3409 )->run($auth, $org_id, $match_copy);
3412 my @canceled_holds; # newly canceled holds
3413 my $chunk_size = 25; # chunked status updates
3415 for my $hold_id (@hold_ids) {
3417 $logger->info("Clear shelf processing hold $hold_id");
3419 my $hold = $e->retrieve_action_hold_request([
3422 flesh_fields => {ahr => ['current_copy']}
3426 if (!$hold->cancel_time) { # may be canceled but still on the holds shelf
3427 $hold->cancel_time('now');
3428 $hold->cancel_cause(2); # Hold Shelf expiration
3429 $e->update_action_hold_request($hold) or return $e->die_event;
3430 delete_hold_copy_maps($self, $e, $hold->id) and return $e->die_event;
3431 push(@canceled_holds, $hold_id);
3434 my $copy = $hold->current_copy;
3436 if($copy_status or $copy_status == 0) {
3437 # if a clear-shelf copy status is defined, update the copy
3438 $copy->status($copy_status);
3439 $copy->edit_date('now');
3440 $copy->editor($e->requestor->id);
3441 $e->update_asset_copy($copy) or return $e->die_event;
3444 push(@holds, $hold);
3445 $client->respond({maximum => scalar(@holds), progress => $counter}) if ( (++$counter % $chunk_size) == 0);
3456 for my $hold (@holds) {
3458 my $copy = $hold->current_copy;
3459 my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
3461 if($alt_hold and !$match_copy) {
3463 push(@{$cache_data{hold}}, $hold->id); # copy is needed for a hold
3465 } elsif($copy->circ_lib != $e->requestor->ws_ou) {
3467 push(@{$cache_data{transit}}, $hold->id); # copy needs to transit
3471 push(@{$cache_data{shelf}}, $hold->id); # copy needs to go back to the shelf
3475 my $cache_key = md5_hex(time . $$ . rand());
3476 $logger->info("clear_shelf_cache: storing under $cache_key");
3477 $cache->put_cache($cache_key, \%cache_data, 7200); # TODO: 2 hours. configurable?
3479 # tell the client we're done
3480 $client->respond_complete({cache_key => $cache_key});
3483 # fire off the hold cancelation trigger and wait for response so don't flood the service
3485 # refetch the holds to pick up the caclulated cancel_time,
3486 # which may be needed by Action/Trigger
3488 my $updated_holds = [];
3489 $updated_holds = $e->search_action_hold_request({id => \@canceled_holds}, {substream => 1}) if (@canceled_holds > 0);
3492 $U->create_events_for_hook(
3493 'hold_request.cancel.expire_holds_shelf',
3494 $_, $org_id, undef, undef, 1) for @$updated_holds;
3497 # tell the client we're done
3498 $client->respond_complete;
3502 __PACKAGE__->register_method(
3503 method => 'usr_hold_summary',
3504 api_name => 'open-ils.circ.holds.user_summary',
3506 Returns a summary of holds statuses for a given user
3510 sub usr_hold_summary {
3511 my($self, $conn, $auth, $user_id) = @_;
3513 my $e = new_editor(authtoken=>$auth);
3514 $e->checkauth or return $e->event;
3515 $e->allowed('VIEW_HOLD') or return $e->event;
3517 my $holds = $e->search_action_hold_request(
3520 fulfillment_time => undef,
3521 cancel_time => undef,
3525 my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
3526 $summary{_hold_status($e, $_)} += 1 for @$holds;
3532 __PACKAGE__->register_method(
3533 method => 'hold_has_copy_at',
3534 api_name => 'open-ils.circ.hold.has_copy_at',
3537 'Returns the ID of the found copy and name of the shelving location if there is ' .
3538 'an available copy at the specified org unit. Returns empty hash otherwise. ' .
3539 'The anticipated use for this method is to determine whether an item is ' .
3540 'available at the library where the user is placing the hold (or, alternatively, '.
3541 'at the pickup library) to encourage bypassing the hold placement and just ' .
3542 'checking out the item.' ,
3544 { desc => 'Authentication Token', type => 'string' },
3545 { desc => 'Method Arguments. Options include: hold_type, hold_target, org_unit. '
3546 . 'hold_type is the hold type code (T, V, C, M, ...). '
3547 . 'hold_target is the identifier of the hold target object. '
3548 . 'org_unit is org unit ID.',
3553 desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
3559 sub hold_has_copy_at {
3560 my($self, $conn, $auth, $args) = @_;
3562 my $e = new_editor(authtoken=>$auth);
3563 $e->checkauth or return $e->event;
3565 my $hold_type = $$args{hold_type};
3566 my $hold_target = $$args{hold_target};
3567 my $org_unit = $$args{org_unit};
3570 select => {acp => ['id'], acpl => ['name']},
3573 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
3574 ccs => {field => 'id', filter => { holdable => 't'}, fkey => 'status' }
3577 where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit, status => [0,7]}},
3581 if($hold_type eq 'C' or $hold_type eq 'F' or $hold_type eq 'R') {
3583 $query->{where}->{'+acp'}->{id} = $hold_target;
3585 } elsif($hold_type eq 'V') {
3587 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3589 } elsif($hold_type eq 'P') {
3591 $query->{from}->{acp}->{acpm} = {
3592 field => 'target_copy',
3594 filter => {part => $hold_target},
3597 } elsif($hold_type eq 'I') {
3599 $query->{from}->{acp}->{sitem} = {
3602 filter => {issuance => $hold_target},
3605 } elsif($hold_type eq 'T') {
3607 $query->{from}->{acp}->{acn} = {
3609 fkey => 'call_number',
3613 filter => {id => $hold_target},
3621 $query->{from}->{acp}->{acn} = {
3623 fkey => 'call_number',
3632 filter => {metarecord => $hold_target},
3640 my $res = $e->json_query($query)->[0] or return {};
3641 return {copy => $res->{id}, location => $res->{name}} if $res;
3645 # returns true if the user already has an item checked out
3646 # that could be used to fulfill the requested hold.
3647 sub hold_item_is_checked_out {
3648 my($e, $user_id, $hold_type, $hold_target) = @_;
3651 select => {acp => ['id']},
3652 from => {acp => {}},
3656 in => { # copies for circs the user has checked out
3657 select => {circ => ['target_copy']},
3661 checkin_time => undef,
3663 {stop_fines => ["MAXFINES","LONGOVERDUE"]},
3664 {stop_fines => undef}
3674 if($hold_type eq 'C' || $hold_type eq 'R' || $hold_type eq 'F') {
3676 $query->{where}->{'+acp'}->{id}->{in}->{where}->{'target_copy'} = $hold_target;
3678 } elsif($hold_type eq 'V') {
3680 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3682 } elsif($hold_type eq 'P') {
3684 $query->{from}->{acp}->{acpm} = {
3685 field => 'target_copy',
3687 filter => {part => $hold_target},
3690 } elsif($hold_type eq 'I') {
3692 $query->{from}->{acp}->{sitem} = {
3695 filter => {issuance => $hold_target},
3698 } elsif($hold_type eq 'T') {
3700 $query->{from}->{acp}->{acn} = {
3702 fkey => 'call_number',
3706 filter => {id => $hold_target},
3714 $query->{from}->{acp}->{acn} = {
3716 fkey => 'call_number',
3725 filter => {metarecord => $hold_target},
3733 return $e->json_query($query)->[0];
3736 __PACKAGE__->register_method(
3737 method => 'change_hold_title',
3738 api_name => 'open-ils.circ.hold.change_title',
3741 Updates all title level holds targeting the specified bibs to point a new bib./,
3743 { desc => 'Authentication Token', type => 'string' },
3744 { desc => 'New Target Bib Id', type => 'number' },
3745 { desc => 'Old Target Bib Ids', type => 'array' },
3747 return => { desc => '1 on success' }
3751 __PACKAGE__->register_method(
3752 method => 'change_hold_title_for_specific_holds',
3753 api_name => 'open-ils.circ.hold.change_title.specific_holds',
3756 Updates specified holds to target new bib./,
3758 { desc => 'Authentication Token', type => 'string' },
3759 { desc => 'New Target Bib Id', type => 'number' },
3760 { desc => 'Holds Ids for holds to update', type => 'array' },
3762 return => { desc => '1 on success' }
3767 sub change_hold_title {
3768 my( $self, $client, $auth, $new_bib_id, $bib_ids ) = @_;
3770 my $e = new_editor(authtoken=>$auth, xact=>1);
3771 return $e->die_event unless $e->checkauth;
3773 my $holds = $e->search_action_hold_request(
3776 cancel_time => undef,
3777 fulfillment_time => undef,
3783 flesh_fields => { ahr => ['usr'] }
3789 for my $hold (@$holds) {
3790 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3791 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3792 $hold->target( $new_bib_id );
3793 $e->update_action_hold_request($hold) or return $e->die_event;
3798 _reset_hold($self, $e->requestor, $_) for @$holds;
3803 sub change_hold_title_for_specific_holds {
3804 my( $self, $client, $auth, $new_bib_id, $hold_ids ) = @_;
3806 my $e = new_editor(authtoken=>$auth, xact=>1);
3807 return $e->die_event unless $e->checkauth;
3809 my $holds = $e->search_action_hold_request(
3812 cancel_time => undef,
3813 fulfillment_time => undef,
3819 flesh_fields => { ahr => ['usr'] }
3825 for my $hold (@$holds) {
3826 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3827 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3828 $hold->target( $new_bib_id );
3829 $e->update_action_hold_request($hold) or return $e->die_event;
3834 _reset_hold($self, $e->requestor, $_) for @$holds;
3839 __PACKAGE__->register_method(
3840 method => 'rec_hold_count',
3841 api_name => 'open-ils.circ.bre.holds.count',
3843 desc => q/Returns the total number of holds that target the
3844 selected bib record or its associated copies and call_numbers/,
3846 { desc => 'Bib ID', type => 'number' },
3848 return => {desc => 'Hold count', type => 'number'}
3852 __PACKAGE__->register_method(
3853 method => 'rec_hold_count',
3854 api_name => 'open-ils.circ.mmr.holds.count',
3856 desc => q/Returns the total number of holds that target the
3857 selected metarecord or its associated copies, call_numbers, and bib records/,
3859 { desc => 'Metarecord ID', type => 'number' },
3861 return => {desc => 'Hold count', type => 'number'}
3865 # XXX Need to add type I (and, soon, type P) holds to these counts
3866 sub rec_hold_count {
3867 my($self, $conn, $target_id) = @_;
3874 filter => {metarecord => $target_id}
3881 filter => { id => $target_id },
3886 if($self->api_name =~ /mmr/) {
3887 delete $bre_join->{bre}->{filter};
3888 $bre_join->{bre}->{join} = $mmr_join;
3894 fkey => 'call_number',
3900 select => {ahr => [{column => 'id', transform => 'count', alias => 'count'}]},
3904 cancel_time => undef,
3905 fulfillment_time => undef,
3909 hold_type => [qw/C F R/],
3912 select => {acp => ['id']},
3913 from => { acp => $cn_join }
3923 select => {acn => ['id']},
3924 from => {acn => $bre_join}
3932 target => $target_id
3940 if($self->api_name =~ /mmr/) {
3941 $query->{where}->{'+ahr'}->{'-or'}->[2] = {
3946 select => {bre => ['id']},
3947 from => {bre => $mmr_join}
3953 $query->{where}->{'+ahr'}->{'-or'}->[3] = {
3956 target => $target_id
3962 return new_editor()->json_query($query)->[0]->{count};