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) {
97 $params->{'depth'} = $res->{'depth'} if $res->{'depth'};
99 my $ahr = construct_hold_request_object($params);
100 my ($res2) = $self->method_lookup(
102 ? 'open-ils.circ.holds.create.override'
103 : 'open-ils.circ.holds.create'
104 )->run($auth, $ahr, $oargs);
106 'target' => $$params{$target_field},
109 $conn->respond($res2);
112 'target' => $$params{$target_field},
115 $conn->respond($res);
121 sub construct_hold_request_object {
124 my $ahr = Fieldmapper::action::hold_request->new;
127 foreach my $field (keys %{ $params }) {
128 if ($field eq 'depth') { $ahr->selection_depth($$params{$field}); }
129 elsif ($field eq 'patronid') {
130 $ahr->usr($$params{$field}); }
131 elsif ($field eq 'titleid') { $ahr->target($$params{$field}); }
132 elsif ($field eq 'copy_id') { $ahr->target($$params{$field}); }
133 elsif ($field eq 'issuanceid') { $ahr->target($$params{$field}); }
134 elsif ($field eq 'volume_id') { $ahr->target($$params{$field}); }
135 elsif ($field eq 'mrid') { $ahr->target($$params{$field}); }
136 elsif ($field eq 'partid') { $ahr->target($$params{$field}); }
138 $ahr->$field($$params{$field});
144 __PACKAGE__->register_method(
145 method => "create_hold_batch",
146 api_name => "open-ils.circ.holds.create.batch",
149 desc => q/@see open-ils.circ.holds.create.batch/,
151 { desc => 'Authentication token', type => 'string' },
152 { desc => 'Array of hold objects', type => 'array' }
155 desc => 'Array of hold ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
160 __PACKAGE__->register_method(
161 method => "create_hold_batch",
162 api_name => "open-ils.circ.holds.create.override.batch",
165 desc => '@see open-ils.circ.holds.create.batch',
170 sub create_hold_batch {
171 my( $self, $conn, $auth, $hold_list, $oargs ) = @_;
172 (my $method = $self->api_name) =~ s/\.batch//og;
173 foreach (@$hold_list) {
174 my ($res) = $self->method_lookup($method)->run($auth, $_, $oargs);
175 $conn->respond($res);
181 __PACKAGE__->register_method(
182 method => "create_hold",
183 api_name => "open-ils.circ.holds.create",
185 desc => "Create a new hold for an item. From a permissions perspective, " .
186 "the login session is used as the 'requestor' of the hold. " .
187 "The hold recipient is determined by the 'usr' setting within the hold object. " .
188 'First we verify the requestor has holds request permissions. ' .
189 'Then we verify that the recipient is allowed to make the given hold. ' .
190 'If not, we see if the requestor has "override" capabilities. If not, ' .
191 'a permission exception is returned. If permissions allow, we cycle ' .
192 'through the set of holds objects and create. ' .
193 'If the recipient does not have permission to place multiple holds ' .
194 'on a single title and said operation is attempted, a permission ' .
195 'exception is returned',
197 { desc => 'Authentication token', type => 'string' },
198 { desc => 'Hold object for hold to be created',
199 type => 'object', class => 'ahr' }
202 desc => 'New ahr ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
207 __PACKAGE__->register_method(
208 method => "create_hold",
209 api_name => "open-ils.circ.holds.create.override",
210 notes => '@see open-ils.circ.holds.create',
212 desc => "If the recipient is not allowed to receive the requested hold, " .
213 "call this method to attempt the override",
215 { desc => 'Authentication token', type => 'string' },
217 desc => 'Hold object for hold to be created',
218 type => 'object', class => 'ahr'
222 desc => 'New hold (ahr) ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
228 my( $self, $conn, $auth, $hold, $oargs ) = @_;
229 return -1 unless $hold;
230 my $e = new_editor(authtoken=>$auth, xact=>1);
231 return $e->die_event unless $e->checkauth;
233 my $override = 1 if $self->api_name =~ /override/;
234 $oargs = { all => 1 } unless defined $oargs;
238 my $requestor = $e->requestor;
239 my $recipient = $requestor;
241 if( $requestor->id ne $hold->usr ) {
242 # Make sure the requestor is allowed to place holds for
243 # the recipient if they are not the same people
244 $recipient = $e->retrieve_actor_user($hold->usr) or return $e->die_event;
245 $e->allowed('REQUEST_HOLDS', $recipient->home_ou) or return $e->die_event;
248 # If the related org setting tells us to, block if patron privs have expired
249 my $expire_setting = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_BLOCK_HOLD_FOR_EXPIRED_PATRON);
250 if ($expire_setting) {
251 my $expire = DateTime::Format::ISO8601->new->parse_datetime(
252 cleanse_ISO8601($recipient->expire_date));
254 push( @events, OpenILS::Event->new(
255 'PATRON_ACCOUNT_EXPIRED',
256 "payload" => {"fail_part" => "actor.usr.privs_expired"}
257 )) if( CORE::time > $expire->epoch ) ;
260 # Now make sure the recipient is allowed to receive the specified hold
261 my $porg = $recipient->home_ou;
262 my $rid = $e->requestor->id;
263 my $t = $hold->hold_type;
265 # See if a duplicate hold already exists
267 usr => $recipient->id,
269 fulfillment_time => undef,
270 target => $hold->target,
271 cancel_time => undef,
274 $sargs->{holdable_formats} = $hold->holdable_formats if $t eq 'M';
276 my $existing = $e->search_action_hold_request($sargs);
277 push( @events, OpenILS::Event->new('HOLD_EXISTS')) if @$existing;
279 my $checked_out = hold_item_is_checked_out($e, $recipient->id, $hold->hold_type, $hold->target);
280 push( @events, OpenILS::Event->new('HOLD_ITEM_CHECKED_OUT')) if $checked_out;
282 if ( $t eq OILS_HOLD_TYPE_METARECORD ) {
283 return $e->die_event unless $e->allowed('MR_HOLDS', $porg);
284 } elsif ( $t eq OILS_HOLD_TYPE_TITLE ) {
285 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
286 } elsif ( $t eq OILS_HOLD_TYPE_VOLUME ) {
287 return $e->die_event unless $e->allowed('VOLUME_HOLDS', $porg);
288 } elsif ( $t eq OILS_HOLD_TYPE_MONOPART ) {
289 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
290 } elsif ( $t eq OILS_HOLD_TYPE_ISSUANCE ) {
291 return $e->die_event unless $e->allowed('ISSUANCE_HOLDS', $porg);
292 } elsif ( $t eq OILS_HOLD_TYPE_COPY ) {
293 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
294 } elsif ( $t eq OILS_HOLD_TYPE_FORCE || $t eq OILS_HOLD_TYPE_RECALL ) {
295 my $copy = $e->retrieve_asset_copy($hold->target)
296 or return $e->die_event;
297 if ( $t eq OILS_HOLD_TYPE_FORCE ) {
298 return $e->die_event unless $e->allowed('COPY_HOLDS_FORCE', $copy->circ_lib);
299 } elsif ( $t eq OILS_HOLD_TYPE_RECALL ) {
300 return $e->die_event unless $e->allowed('COPY_HOLDS_RECALL', $copy->circ_lib);
309 for my $evt (@events) {
311 my $name = $evt->{textcode};
312 if($oargs->{all} || grep { $_ eq $name } @{$oargs->{events}}) {
313 return $e->die_event unless $e->allowed("$name.override", $porg);
321 # Check for hold expiration in the past, and set it to empty string.
322 $hold->expire_time(undef) if ($hold->expire_time && $U->datecmp($hold->expire_time) == -1);
324 # set the configured expire time
325 unless($hold->expire_time) {
326 $hold->expire_time(calculate_expire_time($recipient->home_ou));
329 $hold->requestor($e->requestor->id);
330 $hold->request_lib($e->requestor->ws_ou);
331 $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
332 $hold = $e->create_action_hold_request($hold) or return $e->die_event;
336 $conn->respond_complete($hold->id);
339 'open-ils.storage.action.hold_request.copy_targeter',
340 undef, $hold->id ) unless $U->is_true($hold->frozen);
345 # makes sure that a user has permission to place the type of requested hold
346 # returns the Perm exception if not allowed, returns undef if all is well
347 sub _check_holds_perm {
348 my($type, $user_id, $org_id) = @_;
352 $evt = $apputils->check_perms($user_id, $org_id, "MR_HOLDS" );
353 } elsif ($type eq "T") {
354 $evt = $apputils->check_perms($user_id, $org_id, "TITLE_HOLDS" );
355 } elsif($type eq "V") {
356 $evt = $apputils->check_perms($user_id, $org_id, "VOLUME_HOLDS");
357 } elsif($type eq "C") {
358 $evt = $apputils->check_perms($user_id, $org_id, "COPY_HOLDS" );
365 # tests if the given user is allowed to place holds on another's behalf
366 sub _check_request_holds_perm {
369 if (my $evt = $apputils->check_perms(
370 $user_id, $org_id, "REQUEST_HOLDS")) {
375 my $ses_is_req_note = 'The login session is the requestor. If the requestor is different from the user, ' .
376 'then the requestor must have VIEW_HOLD permissions';
378 __PACKAGE__->register_method(
379 method => "retrieve_holds_by_id",
380 api_name => "open-ils.circ.holds.retrieve_by_id",
382 desc => "Retrieve the hold, with hold transits attached, for the specified ID. $ses_is_req_note",
384 { desc => 'Authentication token', type => 'string' },
385 { desc => 'Hold ID', type => 'number' }
388 desc => 'Hold object with transits attached, event on error',
394 sub retrieve_holds_by_id {
395 my($self, $client, $auth, $hold_id) = @_;
396 my $e = new_editor(authtoken=>$auth);
397 $e->checkauth or return $e->event;
398 $e->allowed('VIEW_HOLD') or return $e->event;
400 my $holds = $e->search_action_hold_request(
402 { id => $hold_id , fulfillment_time => undef },
404 order_by => { ahr => "request_time" },
406 flesh_fields => {ahr => ['notes']}
411 flesh_hold_transits($holds);
412 flesh_hold_notices($holds, $e);
417 __PACKAGE__->register_method(
418 method => "retrieve_holds",
419 api_name => "open-ils.circ.holds.retrieve",
421 desc => "Retrieves all the holds, with hold transits attached, for the specified user. $ses_is_req_note",
423 { desc => 'Authentication token', type => 'string' },
424 { desc => 'User ID', type => 'integer' },
425 { desc => 'Available Only', type => 'boolean' }
428 desc => 'list of holds, event on error',
433 __PACKAGE__->register_method(
434 method => "retrieve_holds",
435 api_name => "open-ils.circ.holds.id_list.retrieve",
438 desc => "Retrieves all the hold IDs, for the specified user. $ses_is_req_note",
440 { desc => 'Authentication token', type => 'string' },
441 { desc => 'User ID', type => 'integer' },
442 { desc => 'Available Only', type => 'boolean' }
445 desc => 'list of holds, event on error',
450 __PACKAGE__->register_method(
451 method => "retrieve_holds",
452 api_name => "open-ils.circ.holds.canceled.retrieve",
455 desc => "Retrieves all the cancelled holds for the specified user. $ses_is_req_note",
457 { desc => 'Authentication token', type => 'string' },
458 { desc => 'User ID', type => 'integer' }
461 desc => 'list of holds, event on error',
466 __PACKAGE__->register_method(
467 method => "retrieve_holds",
468 api_name => "open-ils.circ.holds.canceled.id_list.retrieve",
471 desc => "Retrieves list of cancelled hold IDs for the specified user. $ses_is_req_note",
473 { desc => 'Authentication token', type => 'string' },
474 { desc => 'User ID', type => 'integer' }
477 desc => 'list of hold IDs, event on error',
484 my ($self, $client, $auth, $user_id, $available) = @_;
486 my $e = new_editor(authtoken=>$auth);
487 return $e->event unless $e->checkauth;
488 $user_id = $e->requestor->id unless defined $user_id;
490 my $notes_filter = {staff => 'f'};
491 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
492 unless($user_id == $e->requestor->id) {
493 if($e->allowed('VIEW_HOLD', $user->home_ou)) {
494 $notes_filter = {staff => 't'}
496 my $allowed = OpenILS::Application::Actor::Friends->friend_perm_allowed(
497 $e, $user_id, $e->requestor->id, 'hold.view');
498 return $e->event unless $allowed;
501 # staff member looking at his/her own holds can see staff and non-staff notes
502 $notes_filter = {} if $e->allowed('VIEW_HOLD', $user->home_ou);
506 select => {ahr => ['id']},
508 where => {usr => $user_id, fulfillment_time => undef}
511 if($self->api_name =~ /canceled/) {
513 # Fetch the canceled holds
514 # order cancelled holds by cancel time, most recent first
516 $holds_query->{order_by} = [{class => 'ahr', field => 'cancel_time', direction => 'desc'}];
519 my $cancel_count = $U->ou_ancestor_setting_value(
520 $e->requestor->ws_ou, 'circ.holds.canceled.display_count', $e);
522 unless($cancel_count) {
523 $cancel_age = $U->ou_ancestor_setting_value(
524 $e->requestor->ws_ou, 'circ.holds.canceled.display_age', $e);
526 # if no settings are defined, default to last 10 cancelled holds
527 $cancel_count = 10 unless $cancel_age;
530 if($cancel_count) { # limit by count
532 $holds_query->{where}->{cancel_time} = {'!=' => undef};
533 $holds_query->{limit} = $cancel_count;
535 } elsif($cancel_age) { # limit by age
537 # find all of the canceled holds that were canceled within the configured time frame
538 my $date = DateTime->now->subtract(seconds => OpenSRF::Utils::interval_to_seconds($cancel_age));
539 $date = $U->epoch2ISO8601($date->epoch);
540 $holds_query->{where}->{cancel_time} = {'>=' => $date};
545 # order non-cancelled holds by ready-for-pickup, then active, followed by suspended
546 # "compare" sorts false values to the front. testing pickup_lib != current_shelf_lib
547 # will sort by pl = csl > pl != csl > followed by csl is null;
548 $holds_query->{order_by} = [
550 field => 'pickup_lib',
551 compare => {'!=' => {'+ahr' => 'current_shelf_lib'}}},
552 {class => 'ahr', field => 'shelf_time'},
553 {class => 'ahr', field => 'frozen'},
554 {class => 'ahr', field => 'request_time'}
557 $holds_query->{where}->{cancel_time} = undef;
559 $holds_query->{where}->{shelf_time} = {'!=' => undef};
561 $holds_query->{where}->{pickup_lib} = {'=' => 'current_shelf_lib'};
565 my $hold_ids = $e->json_query($holds_query);
566 $hold_ids = [ map { $_->{id} } @$hold_ids ];
568 return $hold_ids if $self->api_name =~ /id_list/;
571 for my $hold_id ( @$hold_ids ) {
573 my $hold = $e->retrieve_action_hold_request($hold_id);
574 $hold->notes($e->search_action_hold_request_note({hold => $hold_id, %$notes_filter}));
577 $e->search_action_hold_transit_copy([
579 {order_by => {ahtc => 'source_send_time desc'}, limit => 1}])->[0]
589 __PACKAGE__->register_method(
590 method => 'user_hold_count',
591 api_name => 'open-ils.circ.hold.user.count'
594 sub user_hold_count {
595 my ( $self, $conn, $auth, $userid ) = @_;
596 my $e = new_editor( authtoken => $auth );
597 return $e->event unless $e->checkauth;
598 my $patron = $e->retrieve_actor_user($userid)
600 return $e->event unless $e->allowed( 'VIEW_HOLD', $patron->home_ou );
601 return __user_hold_count( $self, $e, $userid );
604 sub __user_hold_count {
605 my ( $self, $e, $userid ) = @_;
606 my $holds = $e->search_action_hold_request(
609 fulfillment_time => undef,
610 cancel_time => undef,
615 return scalar(@$holds);
619 __PACKAGE__->register_method(
620 method => "retrieve_holds_by_pickup_lib",
621 api_name => "open-ils.circ.holds.retrieve_by_pickup_lib",
623 "Retrieves all the holds, with hold transits attached, for the specified pickup_ou id."
626 __PACKAGE__->register_method(
627 method => "retrieve_holds_by_pickup_lib",
628 api_name => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
629 notes => "Retrieves all the hold ids for the specified pickup_ou id. "
632 sub retrieve_holds_by_pickup_lib {
633 my ($self, $client, $login_session, $ou_id) = @_;
635 #FIXME -- put an appropriate permission check here
636 #my( $user, $target, $evt ) = $apputils->checkses_requestor(
637 # $login_session, $user_id, 'VIEW_HOLD' );
638 #return $evt if $evt;
640 my $holds = $apputils->simplereq(
642 "open-ils.cstore.direct.action.hold_request.search.atomic",
644 pickup_lib => $ou_id ,
645 fulfillment_time => undef,
648 { order_by => { ahr => "request_time" } }
651 if ( ! $self->api_name =~ /id_list/ ) {
652 flesh_hold_transits($holds);
656 return [ map { $_->id } @$holds ];
660 __PACKAGE__->register_method(
661 method => "uncancel_hold",
662 api_name => "open-ils.circ.hold.uncancel"
666 my($self, $client, $auth, $hold_id) = @_;
667 my $e = new_editor(authtoken=>$auth, xact=>1);
668 return $e->die_event unless $e->checkauth;
670 my $hold = $e->retrieve_action_hold_request($hold_id)
671 or return $e->die_event;
672 return $e->die_event unless $e->allowed('CANCEL_HOLDS', $hold->request_lib);
674 if ($hold->fulfillment_time) {
678 unless ($hold->cancel_time) {
683 # if configured to reset the request time, also reset the expire time
684 if($U->ou_ancestor_setting_value(
685 $hold->request_lib, 'circ.holds.uncancel.reset_request_time', $e)) {
687 $hold->request_time('now');
688 $hold->expire_time(calculate_expire_time($hold->request_lib));
691 $hold->clear_cancel_time;
692 $hold->clear_cancel_cause;
693 $hold->clear_cancel_note;
694 $hold->clear_shelf_time;
695 $hold->clear_current_copy;
696 $hold->clear_capture_time;
697 $hold->clear_prev_check_time;
698 $hold->clear_shelf_expire_time;
699 $hold->clear_current_shelf_lib;
701 $e->update_action_hold_request($hold) or return $e->die_event;
704 $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
710 __PACKAGE__->register_method(
711 method => "cancel_hold",
712 api_name => "open-ils.circ.hold.cancel",
714 desc => 'Cancels the specified hold. The login session is the requestor. If the requestor is different from the usr field ' .
715 'on the hold, the requestor must have CANCEL_HOLDS permissions. The hold may be either the hold object or the hold id',
717 {desc => 'Authentication token', type => 'string'},
718 {desc => 'Hold ID', type => 'number'},
719 {desc => 'Cause of Cancellation', type => 'string'},
720 {desc => 'Note', type => 'string'}
723 desc => '1 on success, event on error'
729 my($self, $client, $auth, $holdid, $cause, $note) = @_;
731 my $e = new_editor(authtoken=>$auth, xact=>1);
732 return $e->die_event unless $e->checkauth;
734 my $hold = $e->retrieve_action_hold_request($holdid)
735 or return $e->die_event;
737 if( $e->requestor->id ne $hold->usr ) {
738 return $e->die_event unless $e->allowed('CANCEL_HOLDS');
741 if ($hold->cancel_time) {
746 # If the hold is captured, reset the copy status
747 if( $hold->capture_time and $hold->current_copy ) {
749 my $copy = $e->retrieve_asset_copy($hold->current_copy)
750 or return $e->die_event;
752 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
753 $logger->info("canceling hold $holdid whose item is on the holds shelf");
754 # $logger->info("setting copy to status 'reshelving' on hold cancel");
755 # $copy->status(OILS_COPY_STATUS_RESHELVING);
756 # $copy->editor($e->requestor->id);
757 # $copy->edit_date('now');
758 # $e->update_asset_copy($copy) or return $e->event;
760 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
763 $logger->warn("! canceling hold [$hid] that is in transit");
764 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
767 my $trans = $e->retrieve_action_transit_copy($transid);
768 # Leave the transit alive, but set the copy status to
769 # reshelving so it will be properly reshelved when it gets back home
771 $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
772 $e->update_action_transit_copy($trans) or return $e->die_event;
778 $hold->cancel_time('now');
779 $hold->cancel_cause($cause);
780 $hold->cancel_note($note);
781 $e->update_action_hold_request($hold)
782 or return $e->die_event;
784 delete_hold_copy_maps($self, $e, $hold->id);
788 # re-fetch the hold to pick up the real cancel_time (not "now") for A/T
790 $hold = $e->retrieve_action_hold_request($hold->id) or return $e->die_event;
793 if ($e->requestor->id == $hold->usr) {
794 $U->create_events_for_hook('hold_request.cancel.patron', $hold, $hold->pickup_lib);
796 $U->create_events_for_hook('hold_request.cancel.staff', $hold, $hold->pickup_lib);
802 sub delete_hold_copy_maps {
807 my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
809 $editor->delete_action_hold_copy_map($_)
810 or return $editor->event;
816 my $update_hold_desc = 'The login session is the requestor. ' .
817 'If the requestor is different from the usr field on the hold, ' .
818 'the requestor must have UPDATE_HOLDS permissions. ' .
819 'If supplying a hash of hold data, "id" must be included. ' .
820 'The hash is ignored if a hold object is supplied, ' .
821 'so you should supply only one kind of hold data argument.' ;
823 __PACKAGE__->register_method(
824 method => "update_hold",
825 api_name => "open-ils.circ.hold.update",
827 desc => "Updates the specified hold. $update_hold_desc",
829 {desc => 'Authentication token', type => 'string'},
830 {desc => 'Hold Object', type => 'object'},
831 {desc => 'Hash of values to be applied', type => 'object'}
834 desc => 'Hold ID on success, event on error',
840 __PACKAGE__->register_method(
841 method => "batch_update_hold",
842 api_name => "open-ils.circ.hold.update.batch",
845 desc => "Updates the specified hold(s). $update_hold_desc",
847 {desc => 'Authentication token', type => 'string'},
848 {desc => 'Array of hold obejcts', type => 'array' },
849 {desc => 'Array of hashes of values to be applied', type => 'array' }
852 desc => 'Hold ID per success, event per error',
858 my($self, $client, $auth, $hold, $values) = @_;
859 my $e = new_editor(authtoken=>$auth, xact=>1);
860 return $e->die_event unless $e->checkauth;
861 my $resp = update_hold_impl($self, $e, $hold, $values);
862 if ($U->event_code($resp)) {
866 $e->commit; # FIXME: update_hold_impl already does $e->commit ??
870 sub batch_update_hold {
871 my($self, $client, $auth, $hold_list, $values_list) = @_;
872 my $e = new_editor(authtoken=>$auth);
873 return $e->die_event unless $e->checkauth;
875 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.
877 $values_list ||= []; # FIXME: either move this above $count declaration, or send an event if both lists undef. Probably the latter.
879 # FIXME: Failing over to [] guarantees warnings for "Use of unitialized value" in update_hold_impl call.
880 # FIXME: We should be sure we only call update_hold_impl with hold object OR hash, not both.
882 for my $idx (0..$count-1) {
884 my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
885 $e->xact_commit unless $U->event_code($resp);
886 $client->respond($resp);
890 return undef; # not in the register return type, assuming we should always have at least one list populated
893 sub update_hold_impl {
894 my($self, $e, $hold, $values) = @_;
896 my $need_retarget = 0;
899 $hold = $e->retrieve_action_hold_request($values->{id})
900 or return $e->die_event;
901 for my $k (keys %$values) {
902 # Outside of pickup_lib (covered by the first regex) I don't know when these would currently change.
903 # But hey, why not cover things that may happen later?
904 if ($k =~ '_(lib|ou)$' || $k eq 'target' || $k eq 'hold_type' || $k eq 'requestor' || $k eq 'selection_depth' || $k eq 'holdable_formats') {
905 if (defined $values->{$k} && defined $hold->$k() && $values->{$k} ne $hold->$k()) {
906 # Value changed? RETARGET!
908 } elsif (defined $hold->$k() != defined $values->{$k}) {
909 # Value being set or cleared? RETARGET!
913 if (defined $values->{$k}) {
914 $hold->$k($values->{$k});
916 my $f = "clear_$k"; $hold->$f();
921 my $orig_hold = $e->retrieve_action_hold_request($hold->id)
922 or return $e->die_event;
924 # don't allow the user to be changed
925 return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
927 if($hold->usr ne $e->requestor->id) {
928 # if the hold is for a different user, make sure the
929 # requestor has the appropriate permissions
930 my $usr = $e->retrieve_actor_user($hold->usr)
931 or return $e->die_event;
932 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
936 # --------------------------------------------------------------
937 # Changing the request time is like playing God
938 # --------------------------------------------------------------
939 if($hold->request_time ne $orig_hold->request_time) {
940 return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
941 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
945 # --------------------------------------------------------------
946 # Code for making sure staff have appropriate permissons for cut_in_line
947 # This, as is, doesn't prevent a user from cutting their own holds in line
949 # --------------------------------------------------------------
950 if($U->is_true($hold->cut_in_line) ne $U->is_true($orig_hold->cut_in_line)) {
951 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
955 # --------------------------------------------------------------
956 # Disallow hold suspencion if the hold is already captured.
957 # --------------------------------------------------------------
958 if ($U->is_true($hold->frozen) and not $U->is_true($orig_hold->frozen)) {
959 $hold_status = _hold_status($e, $hold);
960 if ($hold_status > 2 && $hold_status != 7) { # hold is captured
961 $logger->info("bypassing hold freeze on captured hold");
962 return OpenILS::Event->new('HOLD_SUSPEND_AFTER_CAPTURE');
967 # --------------------------------------------------------------
968 # if the hold is on the holds shelf or in transit and the pickup
969 # lib changes we need to create a new transit.
970 # --------------------------------------------------------------
971 if($orig_hold->pickup_lib ne $hold->pickup_lib) {
973 $hold_status = _hold_status($e, $hold) unless $hold_status;
975 if($hold_status == 3) { # in transit
977 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
978 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
980 $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
982 # update the transit to reflect the new pickup location
983 my $transit = $e->search_action_hold_transit_copy(
984 {hold=>$hold->id, dest_recv_time => undef})->[0]
985 or return $e->die_event;
987 $transit->prev_dest($transit->dest); # mark the previous destination on the transit
988 $transit->dest($hold->pickup_lib);
989 $e->update_action_hold_transit_copy($transit) or return $e->die_event;
991 } elsif($hold_status == 4 or $hold_status == 5 or $hold_status == 8) { # on holds shelf
993 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
994 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
996 $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
998 if ($hold->pickup_lib eq $orig_hold->current_shelf_lib) {
999 # This can happen if the pickup lib is changed while the hold is
1000 # on the shelf, then changed back to the original pickup lib.
1001 # Restore the original shelf_expire_time to prevent abuse.
1002 set_hold_shelf_expire_time(undef, $hold, $e, $hold->shelf_time);
1005 # clear to prevent premature shelf expiration
1006 $hold->clear_shelf_expire_time;
1011 if($U->is_true($hold->frozen)) {
1012 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
1013 $hold->clear_current_copy;
1014 $hold->clear_prev_check_time;
1015 # Clear expire_time to prevent frozen holds from expiring.
1016 $logger->info("clearing expire_time for frozen hold ".$hold->id);
1017 $hold->clear_expire_time;
1020 # If the hold_expire_time is in the past && is not equal to the
1021 # original expire_time, then reset the expire time to be in the
1023 if ($hold->expire_time && $U->datecmp($hold->expire_time) == -1 && $U->datecmp($hold->expire_time, $orig_hold->expire_time) != 0) {
1024 $hold->expire_time(calculate_expire_time($hold->request_lib));
1027 # If the hold is reactivated, reset the expire_time.
1028 if(!$U->is_true($hold->frozen) && $U->is_true($orig_hold->frozen)) {
1029 $logger->info("Reset expire_time on activated hold ".$hold->id);
1030 $hold->expire_time(calculate_expire_time($hold->request_lib));
1033 $e->update_action_hold_request($hold) or return $e->die_event;
1036 if(!$U->is_true($hold->frozen) && $U->is_true($orig_hold->frozen)) {
1037 $logger->info("Running targeter on activated hold ".$hold->id);
1038 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1041 # a change to mint-condition changes the set of potential copies, so retarget the hold;
1042 if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
1043 _reset_hold($self, $e->requestor, $hold)
1044 } elsif($need_retarget && !defined $hold->capture_time()) { # If needed, retarget the hold due to changes
1046 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1052 # this does not update the hold in the DB. It only
1053 # sets the shelf_expire_time field on the hold object.
1054 # start_time is optional and defaults to 'now'
1055 sub set_hold_shelf_expire_time {
1056 my ($class, $hold, $editor, $start_time) = @_;
1058 my $shelf_expire = $U->ou_ancestor_setting_value(
1060 'circ.holds.default_shelf_expire_interval',
1064 return undef unless $shelf_expire;
1066 $start_time = ($start_time) ?
1067 DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time)) :
1070 my $seconds = OpenSRF::Utils->interval_to_seconds($shelf_expire);
1071 my $expire_time = $start_time->add(seconds => $seconds);
1073 # if the shelf expire time overlaps with a pickup lib's
1074 # closed date, push it out to the first open date
1075 my $dateinfo = $U->storagereq(
1076 'open-ils.storage.actor.org_unit.closed_date.overlap',
1077 $hold->pickup_lib, $expire_time->strftime('%FT%T%z'));
1080 my $dt_parser = DateTime::Format::ISO8601->new;
1081 $expire_time = $dt_parser->parse_datetime(cleanse_ISO8601($dateinfo->{end}));
1083 # TODO: enable/disable time bump via setting?
1084 $expire_time->set(hour => '23', minute => '59', second => '59');
1086 $logger->info("circulator: shelf_expire_time overlaps".
1087 " with closed date, pushing expire time to $expire_time");
1090 $hold->shelf_expire_time($expire_time->strftime('%FT%T%z'));
1096 my($e, $orig_hold, $hold, $copy) = @_;
1097 my $src = $orig_hold->pickup_lib;
1098 my $dest = $hold->pickup_lib;
1100 $logger->info("putting hold into transit on pickup_lib update");
1102 my $transit = Fieldmapper::action::hold_transit_copy->new;
1103 $transit->hold($hold->id);
1104 $transit->source($src);
1105 $transit->dest($dest);
1106 $transit->target_copy($copy->id);
1107 $transit->source_send_time('now');
1108 $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
1110 $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
1111 $copy->editor($e->requestor->id);
1112 $copy->edit_date('now');
1114 $e->create_action_hold_transit_copy($transit) or return $e->die_event;
1115 $e->update_asset_copy($copy) or return $e->die_event;
1119 # if the hold is frozen, this method ensures that the hold is not "targeted",
1120 # that is, it clears the current_copy and prev_check_time to essentiallly
1121 # reset the hold. If it is being activated, it runs the targeter in the background
1122 sub update_hold_if_frozen {
1123 my($self, $e, $hold, $orig_hold) = @_;
1124 return if $hold->capture_time;
1126 if($U->is_true($hold->frozen)) {
1127 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
1128 $hold->clear_current_copy;
1129 $hold->clear_prev_check_time;
1132 if($U->is_true($orig_hold->frozen)) {
1133 $logger->info("Running targeter on activated hold ".$hold->id);
1134 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1139 __PACKAGE__->register_method(
1140 method => "hold_note_CUD",
1141 api_name => "open-ils.circ.hold_request.note.cud",
1143 desc => 'Create, update or delete a hold request note. If the operator (from Auth. token) '
1144 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
1146 { desc => 'Authentication token', type => 'string' },
1147 { desc => 'Hold note object', type => 'object' }
1150 desc => 'Returns the note ID, event on error'
1156 my($self, $conn, $auth, $note) = @_;
1158 my $e = new_editor(authtoken => $auth, xact => 1);
1159 return $e->die_event unless $e->checkauth;
1161 my $hold = $e->retrieve_action_hold_request($note->hold)
1162 or return $e->die_event;
1164 if($hold->usr ne $e->requestor->id) {
1165 my $usr = $e->retrieve_actor_user($hold->usr);
1166 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
1167 $note->staff('t') if $note->isnew;
1171 $e->create_action_hold_request_note($note) or return $e->die_event;
1172 } elsif($note->ischanged) {
1173 $e->update_action_hold_request_note($note) or return $e->die_event;
1174 } elsif($note->isdeleted) {
1175 $e->delete_action_hold_request_note($note) or return $e->die_event;
1183 __PACKAGE__->register_method(
1184 method => "retrieve_hold_status",
1185 api_name => "open-ils.circ.hold.status.retrieve",
1187 desc => 'Calculates the current status of the hold. The requestor must have ' .
1188 'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
1190 { desc => 'Hold ID', type => 'number' }
1193 # type => 'number', # event sometimes
1194 desc => <<'END_OF_DESC'
1195 Returns event on error or:
1196 -1 on error (for now),
1197 1 for 'waiting for copy to become available',
1198 2 for 'waiting for copy capture',
1201 5 for 'hold-shelf-delay'
1204 8 for 'captured, on wrong hold shelf'
1210 sub retrieve_hold_status {
1211 my($self, $client, $auth, $hold_id) = @_;
1213 my $e = new_editor(authtoken => $auth);
1214 return $e->event unless $e->checkauth;
1215 my $hold = $e->retrieve_action_hold_request($hold_id)
1216 or return $e->event;
1218 if( $e->requestor->id != $hold->usr ) {
1219 return $e->event unless $e->allowed('VIEW_HOLD');
1222 return _hold_status($e, $hold);
1228 if ($hold->cancel_time) {
1231 if ($U->is_true($hold->frozen) && !$hold->capture_time) {
1234 if ($hold->current_shelf_lib and $hold->current_shelf_lib ne $hold->pickup_lib) {
1237 return 1 unless $hold->current_copy;
1238 return 2 unless $hold->capture_time;
1240 my $copy = $hold->current_copy;
1241 unless( ref $copy ) {
1242 $copy = $e->retrieve_asset_copy($hold->current_copy)
1243 or return $e->event;
1246 return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
1248 if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
1250 my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
1251 return 4 unless $hs_wait_interval;
1253 # if a hold_shelf_status_delay interval is defined and start_time plus
1254 # the interval is greater than now, consider the hold to be in the virtual
1255 # "on its way to the holds shelf" status. Return 5.
1257 my $transit = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
1258 my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
1259 $start_time = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
1260 my $end_time = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
1262 return 5 if $end_time > DateTime->now;
1271 __PACKAGE__->register_method(
1272 method => "retrieve_hold_queue_stats",
1273 api_name => "open-ils.circ.hold.queue_stats.retrieve",
1275 desc => 'Returns summary data about the state of a hold',
1277 { desc => 'Authentication token', type => 'string'},
1278 { desc => 'Hold ID', type => 'number'},
1281 desc => q/Summary object with keys:
1282 total_holds : total holds in queue
1283 queue_position : current queue position
1284 potential_copies : number of potential copies for this hold
1285 estimated_wait : estimated wait time in days
1286 status : hold status
1287 -1 => error or unexpected state,
1288 1 => 'waiting for copy to become available',
1289 2 => 'waiting for copy capture',
1292 5 => 'hold-shelf-delay'
1299 sub retrieve_hold_queue_stats {
1300 my($self, $conn, $auth, $hold_id) = @_;
1301 my $e = new_editor(authtoken => $auth);
1302 return $e->event unless $e->checkauth;
1303 my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1304 if($e->requestor->id != $hold->usr) {
1305 return $e->event unless $e->allowed('VIEW_HOLD');
1307 return retrieve_hold_queue_status_impl($e, $hold);
1310 sub retrieve_hold_queue_status_impl {
1314 # The holds queue is defined as the distinct set of holds that share at
1315 # least one potential copy with the context hold, plus any holds that
1316 # share the same hold type and target. The latter part exists to
1317 # accomodate holds that currently have no potential copies
1318 my $q_holds = $e->json_query({
1320 # fetch cut_in_line and request_time since they're in the order_by
1321 # and we're asking for distinct values
1322 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1329 'field' => 'target_copy',
1330 'fkey' => 'target_copy'
1339 "field" => "cut_in_line",
1340 "transform" => "coalesce",
1342 "direction" => "desc"
1344 { "class" => "ahr", "field" => "request_time" }
1348 '+ahcm2' => { hold => $hold->id }
1352 if (!@$q_holds) { # none? maybe we don't have a map ...
1353 $q_holds = $e->json_query({
1354 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1359 "field" => "cut_in_line",
1360 "transform" => "coalesce",
1362 "direction" => "desc"
1364 { "class" => "ahr", "field" => "request_time" }
1367 hold_type => $hold->hold_type,
1368 target => $hold->target
1375 for my $h (@$q_holds) {
1376 last if $h->{id} == $hold->id;
1380 my $hold_data = $e->json_query({
1382 acp => [ {column => 'id', transform => 'count', aggregate => 1, alias => 'count'} ],
1383 ccm => [ {column =>'avg_wait_time'} ]
1389 ccm => {type => 'left'}
1394 where => {'+ahcm' => {hold => $hold->id} }
1397 my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1399 my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1400 my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1401 $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1402 $default_wait ||= '0 seconds';
1404 # Estimated wait time is the average wait time across the set
1405 # of potential copies, divided by the number of potential copies
1406 # times the queue position.
1408 my $combined_secs = 0;
1409 my $num_potentials = 0;
1411 for my $wait_data (@$hold_data) {
1412 my $count += $wait_data->{count};
1413 $combined_secs += $count *
1414 OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1415 $num_potentials += $count;
1418 my $estimated_wait = -1;
1420 if($num_potentials) {
1421 my $avg_wait = $combined_secs / $num_potentials;
1422 $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1423 $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1427 total_holds => scalar(@$q_holds),
1428 queue_position => $qpos,
1429 potential_copies => $num_potentials,
1430 status => _hold_status( $e, $hold ),
1431 estimated_wait => int($estimated_wait)
1436 sub fetch_open_hold_by_current_copy {
1439 my $hold = $apputils->simplereq(
1441 'open-ils.cstore.direct.action.hold_request.search.atomic',
1442 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1443 return $hold->[0] if ref($hold);
1447 sub fetch_related_holds {
1450 return $apputils->simplereq(
1452 'open-ils.cstore.direct.action.hold_request.search.atomic',
1453 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1457 __PACKAGE__->register_method(
1458 method => "hold_pull_list",
1459 api_name => "open-ils.circ.hold_pull_list.retrieve",
1461 desc => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1462 'The location is determined by the login session.',
1464 { desc => 'Limit (optional)', type => 'number'},
1465 { desc => 'Offset (optional)', type => 'number'},
1468 desc => 'reference to a list of holds, or event on failure',
1473 __PACKAGE__->register_method(
1474 method => "hold_pull_list",
1475 api_name => "open-ils.circ.hold_pull_list.id_list.retrieve",
1477 desc => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1478 'The location is determined by the login session.',
1480 { desc => 'Limit (optional)', type => 'number'},
1481 { desc => 'Offset (optional)', type => 'number'},
1484 desc => 'reference to a list of holds, or event on failure',
1489 __PACKAGE__->register_method(
1490 method => "hold_pull_list",
1491 api_name => "open-ils.circ.hold_pull_list.retrieve.count",
1493 desc => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1494 'The location is determined by the login session.',
1496 { desc => 'Limit (optional)', type => 'number'},
1497 { desc => 'Offset (optional)', type => 'number'},
1500 desc => 'Holds count (integer), or event on failure',
1507 sub hold_pull_list {
1508 my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1509 my( $reqr, $evt ) = $U->checkses($authtoken);
1510 return $evt if $evt;
1512 my $org = $reqr->ws_ou || $reqr->home_ou;
1513 # the perm locaiton shouldn't really matter here since holds
1514 # will exist all over and VIEW_HOLDS should be universal
1515 $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1516 return $evt if $evt;
1518 if($self->api_name =~ /count/) {
1520 my $count = $U->storagereq(
1521 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1522 $org, $limit, $offset );
1524 $logger->info("Grabbing pull list for org unit $org with $count items");
1527 } elsif( $self->api_name =~ /id_list/ ) {
1528 return $U->storagereq(
1529 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1530 $org, $limit, $offset );
1533 return $U->storagereq(
1534 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1535 $org, $limit, $offset );
1539 __PACKAGE__->register_method(
1540 method => "print_hold_pull_list",
1541 api_name => "open-ils.circ.hold_pull_list.print",
1543 desc => 'Returns an HTML-formatted holds pull list',
1545 { desc => 'Authtoken', type => 'string'},
1546 { desc => 'Org unit ID. Optional, defaults to workstation org unit', type => 'number'},
1549 desc => 'HTML string',
1555 sub print_hold_pull_list {
1556 my($self, $client, $auth, $org_id) = @_;
1558 my $e = new_editor(authtoken=>$auth);
1559 return $e->event unless $e->checkauth;
1561 $org_id = (defined $org_id) ? $org_id : $e->requestor->ws_ou;
1562 return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1564 my $hold_ids = $U->storagereq(
1565 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1568 return undef unless @$hold_ids;
1570 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1572 # Holds will /NOT/ be in order after this ...
1573 my $holds = $e->search_action_hold_request({id => $hold_ids}, {substream => 1});
1574 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1576 # ... so we must resort.
1577 my $hold_map = +{map { $_->id => $_ } @$holds};
1578 my $sorted_holds = [];
1579 push @$sorted_holds, $hold_map->{$_} foreach @$hold_ids;
1581 return $U->fire_object_event(
1582 undef, "ahr.format.pull_list", $sorted_holds,
1583 $org_id, undef, undef, $client
1588 __PACKAGE__->register_method(
1589 method => "print_hold_pull_list_stream",
1591 api_name => "open-ils.circ.hold_pull_list.print.stream",
1593 desc => 'Returns a stream of fleshed holds',
1595 { desc => 'Authtoken', type => 'string'},
1596 { 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)',
1601 desc => 'A stream of fleshed holds',
1607 sub print_hold_pull_list_stream {
1608 my($self, $client, $auth, $params) = @_;
1610 my $e = new_editor(authtoken=>$auth);
1611 return $e->die_event unless $e->checkauth;
1613 delete($$params{org_id}) unless (int($$params{org_id}));
1614 delete($$params{limit}) unless (int($$params{limit}));
1615 delete($$params{offset}) unless (int($$params{offset}));
1616 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1617 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1618 $$params{chunk_size} ||= 10;
1620 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1621 return $e->die_event unless $e->allowed('VIEW_HOLD', $$params{org_id });
1624 if ($$params{sort} && @{ $$params{sort} }) {
1625 for my $s (@{ $$params{sort} }) {
1626 if ($s eq 'acplo.position') {
1628 "class" => "acplo", "field" => "position",
1629 "transform" => "coalesce", "params" => [999]
1631 } elsif ($s eq 'prefix') {
1632 push @$sort, {"class" => "acnp", "field" => "label_sortkey"};
1633 } elsif ($s eq 'call_number') {
1634 push @$sort, {"class" => "acn", "field" => "label_sortkey"};
1635 } elsif ($s eq 'suffix') {
1636 push @$sort, {"class" => "acns", "field" => "label_sortkey"};
1637 } elsif ($s eq 'request_time') {
1638 push @$sort, {"class" => "ahr", "field" => "request_time"};
1642 push @$sort, {"class" => "ahr", "field" => "request_time"};
1645 my $holds_ids = $e->json_query(
1647 "select" => {"ahr" => ["id"]},
1652 "fkey" => "current_copy",
1654 "circ_lib" => $$params{org_id}, "status" => [0,7]
1659 "fkey" => "call_number",
1673 "fkey" => "circ_lib",
1676 "location" => {"=" => {"+acp" => "location"}}
1685 "capture_time" => undef,
1686 "cancel_time" => undef,
1688 {"expire_time" => undef },
1689 {"expire_time" => {">" => "now"}}
1693 (@$sort ? (order_by => $sort) : ()),
1694 ($$params{limit} ? (limit => $$params{limit}) : ()),
1695 ($$params{offset} ? (offset => $$params{offset}) : ())
1696 }, {"substream" => 1}
1697 ) or return $e->die_event;
1699 $logger->info("about to stream back " . scalar(@$holds_ids) . " holds");
1702 for my $hid (@$holds_ids) {
1703 push @chunk, $e->retrieve_action_hold_request([
1707 "ahr" => ["usr", "current_copy"],
1709 "acp" => ["location", "call_number", "parts"],
1710 "acn" => ["record","prefix","suffix"]
1715 if (@chunk >= $$params{chunk_size}) {
1716 $client->respond( \@chunk );
1720 $client->respond_complete( \@chunk ) if (@chunk);
1727 __PACKAGE__->register_method(
1728 method => 'fetch_hold_notify',
1729 api_name => 'open-ils.circ.hold_notification.retrieve_by_hold',
1732 Returns a list of hold notification objects based on hold id.
1733 @param authtoken The loggin session key
1734 @param holdid The id of the hold whose notifications we want to retrieve
1735 @return An array of hold notification objects, event on error.
1739 sub fetch_hold_notify {
1740 my( $self, $conn, $authtoken, $holdid ) = @_;
1741 my( $requestor, $evt ) = $U->checkses($authtoken);
1742 return $evt if $evt;
1743 my ($hold, $patron);
1744 ($hold, $evt) = $U->fetch_hold($holdid);
1745 return $evt if $evt;
1746 ($patron, $evt) = $U->fetch_user($hold->usr);
1747 return $evt if $evt;
1749 $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1750 return $evt if $evt;
1752 $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1753 return $U->cstorereq(
1754 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1758 __PACKAGE__->register_method(
1759 method => 'create_hold_notify',
1760 api_name => 'open-ils.circ.hold_notification.create',
1762 Creates a new hold notification object
1763 @param authtoken The login session key
1764 @param notification The hold notification object to create
1765 @return ID of the new object on success, Event on error
1769 sub create_hold_notify {
1770 my( $self, $conn, $auth, $note ) = @_;
1771 my $e = new_editor(authtoken=>$auth, xact=>1);
1772 return $e->die_event unless $e->checkauth;
1774 my $hold = $e->retrieve_action_hold_request($note->hold)
1775 or return $e->die_event;
1776 my $patron = $e->retrieve_actor_user($hold->usr)
1777 or return $e->die_event;
1779 return $e->die_event unless
1780 $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1782 $note->notify_staff($e->requestor->id);
1783 $e->create_action_hold_notification($note) or return $e->die_event;
1788 __PACKAGE__->register_method(
1789 method => 'create_hold_note',
1790 api_name => 'open-ils.circ.hold_note.create',
1792 Creates a new hold request note object
1793 @param authtoken The login session key
1794 @param note The hold note object to create
1795 @return ID of the new object on success, Event on error
1799 sub create_hold_note {
1800 my( $self, $conn, $auth, $note ) = @_;
1801 my $e = new_editor(authtoken=>$auth, xact=>1);
1802 return $e->die_event unless $e->checkauth;
1804 my $hold = $e->retrieve_action_hold_request($note->hold)
1805 or return $e->die_event;
1806 my $patron = $e->retrieve_actor_user($hold->usr)
1807 or return $e->die_event;
1809 return $e->die_event unless
1810 $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn. Probably want something more specific
1812 $e->create_action_hold_request_note($note) or return $e->die_event;
1817 __PACKAGE__->register_method(
1818 method => 'reset_hold',
1819 api_name => 'open-ils.circ.hold.reset',
1821 Un-captures and un-targets a hold, essentially returning
1822 it to the state it was in directly after it was placed,
1823 then attempts to re-target the hold
1824 @param authtoken The login session key
1825 @param holdid The id of the hold
1831 my( $self, $conn, $auth, $holdid ) = @_;
1833 my ($hold, $evt) = $U->fetch_hold($holdid);
1834 return $evt if $evt;
1835 ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1836 return $evt if $evt;
1837 $evt = _reset_hold($self, $reqr, $hold);
1838 return $evt if $evt;
1843 __PACKAGE__->register_method(
1844 method => 'reset_hold_batch',
1845 api_name => 'open-ils.circ.hold.reset.batch'
1848 sub reset_hold_batch {
1849 my($self, $conn, $auth, $hold_ids) = @_;
1851 my $e = new_editor(authtoken => $auth);
1852 return $e->event unless $e->checkauth;
1854 for my $hold_id ($hold_ids) {
1856 my $hold = $e->retrieve_action_hold_request(
1857 [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}])
1858 or return $e->event;
1860 next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1861 _reset_hold($self, $e->requestor, $hold);
1869 my ($self, $reqr, $hold) = @_;
1871 my $e = new_editor(xact =>1, requestor => $reqr);
1873 $logger->info("reseting hold ".$hold->id);
1875 my $hid = $hold->id;
1877 if( $hold->capture_time and $hold->current_copy ) {
1879 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1880 or return $e->die_event;
1882 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1883 $logger->info("setting copy to status 'reshelving' on hold retarget");
1884 $copy->status(OILS_COPY_STATUS_RESHELVING);
1885 $copy->editor($e->requestor->id);
1886 $copy->edit_date('now');
1887 $e->update_asset_copy($copy) or return $e->die_event;
1889 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1891 # We don't want the copy to remain "in transit"
1892 $copy->status(OILS_COPY_STATUS_RESHELVING);
1893 $logger->warn("! reseting hold [$hid] that is in transit");
1894 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1897 my $trans = $e->retrieve_action_transit_copy($transid);
1899 $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1900 my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1, 1);
1901 $logger->info("Transit abort completed with result $evt");
1902 unless ("$evt" eq 1) {
1911 $hold->clear_capture_time;
1912 $hold->clear_current_copy;
1913 $hold->clear_shelf_time;
1914 $hold->clear_shelf_expire_time;
1915 $hold->clear_current_shelf_lib;
1917 $e->update_action_hold_request($hold) or return $e->die_event;
1921 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1927 __PACKAGE__->register_method(
1928 method => 'fetch_open_title_holds',
1929 api_name => 'open-ils.circ.open_holds.retrieve',
1931 Returns a list ids of un-fulfilled holds for a given title id
1932 @param authtoken The login session key
1933 @param id the id of the item whose holds we want to retrieve
1934 @param type The hold type - M, T, I, V, C, F, R
1938 sub fetch_open_title_holds {
1939 my( $self, $conn, $auth, $id, $type, $org ) = @_;
1940 my $e = new_editor( authtoken => $auth );
1941 return $e->event unless $e->checkauth;
1944 $org ||= $e->requestor->ws_ou;
1946 # return $e->search_action_hold_request(
1947 # { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1949 # XXX make me return IDs in the future ^--
1950 my $holds = $e->search_action_hold_request(
1953 cancel_time => undef,
1955 fulfillment_time => undef
1959 flesh_hold_transits($holds);
1964 sub flesh_hold_transits {
1966 for my $hold ( @$holds ) {
1968 $apputils->simplereq(
1970 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1971 { hold => $hold->id },
1972 { order_by => { ahtc => 'id desc' }, limit => 1 }
1978 sub flesh_hold_notices {
1979 my( $holds, $e ) = @_;
1980 $e ||= new_editor();
1982 for my $hold (@$holds) {
1983 my $notices = $e->search_action_hold_notification(
1985 { hold => $hold->id },
1986 { order_by => { anh => 'notify_time desc' } },
1991 $hold->notify_count(scalar(@$notices));
1993 my $n = $e->retrieve_action_hold_notification($$notices[0])
1994 or return $e->event;
1995 $hold->notify_time($n->notify_time);
2001 __PACKAGE__->register_method(
2002 method => 'fetch_captured_holds',
2003 api_name => 'open-ils.circ.captured_holds.on_shelf.retrieve',
2007 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
2008 @param authtoken The login session key
2009 @param org The org id of the location in question
2010 @param match_copy A specific copy to limit to
2014 __PACKAGE__->register_method(
2015 method => 'fetch_captured_holds',
2016 api_name => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
2020 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
2021 @param authtoken The login session key
2022 @param org The org id of the location in question
2023 @param match_copy A specific copy to limit to
2027 __PACKAGE__->register_method(
2028 method => 'fetch_captured_holds',
2029 api_name => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
2033 Returns list ids of shelf-expired un-fulfilled holds for a given title id
2034 @param authtoken The login session key
2035 @param org The org id of the location in question
2036 @param match_copy A specific copy to limit to
2041 sub fetch_captured_holds {
2042 my( $self, $conn, $auth, $org, $match_copy ) = @_;
2044 my $e = new_editor(authtoken => $auth);
2045 return $e->die_event unless $e->checkauth;
2046 return $e->die_event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
2048 $org ||= $e->requestor->ws_ou;
2050 my $current_copy = { '!=' => undef };
2051 $current_copy = { '=' => $match_copy } if $match_copy;
2054 select => { alhr => ['id'] },
2059 fkey => 'current_copy'
2064 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
2066 capture_time => { "!=" => undef },
2067 current_copy => $current_copy,
2068 fulfillment_time => undef,
2069 current_shelf_lib => $org
2073 if($self->api_name =~ /expired/) {
2074 $query->{'where'}->{'+alhr'}->{'-or'} = {
2075 shelf_expire_time => { '<' => 'now'},
2076 cancel_time => { '!=' => undef },
2079 my $hold_ids = $e->json_query( $query );
2081 for my $hold_id (@$hold_ids) {
2082 if($self->api_name =~ /id_list/) {
2083 $conn->respond($hold_id->{id});
2087 $e->retrieve_action_hold_request([
2091 flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
2092 order_by => {anh => 'notify_time desc'}
2102 __PACKAGE__->register_method(
2103 method => "print_expired_holds_stream",
2104 api_name => "open-ils.circ.captured_holds.expired.print.stream",
2108 sub print_expired_holds_stream {
2109 my ($self, $client, $auth, $params) = @_;
2111 # No need to check specific permissions: we're going to call another method
2112 # that will do that.
2113 my $e = new_editor("authtoken" => $auth);
2114 return $e->die_event unless $e->checkauth;
2116 delete($$params{org_id}) unless (int($$params{org_id}));
2117 delete($$params{limit}) unless (int($$params{limit}));
2118 delete($$params{offset}) unless (int($$params{offset}));
2119 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
2120 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
2121 $$params{chunk_size} ||= 10;
2123 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
2125 my @hold_ids = $self->method_lookup(
2126 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
2127 )->run($auth, $params->{"org_id"});
2132 } elsif (defined $U->event_code($hold_ids[0])) {
2134 return $hold_ids[0];
2137 $logger->info("about to stream back up to " . scalar(@hold_ids) . " expired holds");
2140 my @hid_chunk = splice @hold_ids, 0, $params->{"chunk_size"};
2142 my $result_chunk = $e->json_query({
2144 "acp" => ["barcode"],
2146 first_given_name second_given_name family_name alias
2155 "field" => "id", "fkey" => "current_copy",
2158 "field" => "id", "fkey" => "call_number",
2161 "field" => "id", "fkey" => "record"
2165 "acpl" => {"field" => "id", "fkey" => "location"}
2168 "au" => {"field" => "id", "fkey" => "usr"}
2171 "where" => {"+ahr" => {"id" => \@hid_chunk}}
2172 }) or return $e->die_event;
2173 $client->respond($result_chunk);
2180 __PACKAGE__->register_method(
2181 method => "check_title_hold_batch",
2182 api_name => "open-ils.circ.title_hold.is_possible.batch",
2185 desc => '@see open-ils.circ.title_hold.is_possible.batch',
2187 { desc => 'Authentication token', type => 'string'},
2188 { desc => 'Array of Hash of named parameters', type => 'array'},
2191 desc => 'Array of response objects',
2197 sub check_title_hold_batch {
2198 my($self, $client, $authtoken, $param_list, $oargs) = @_;
2199 foreach (@$param_list) {
2200 my ($res) = $self->method_lookup('open-ils.circ.title_hold.is_possible')->run($authtoken, $_, $oargs);
2201 $client->respond($res);
2207 __PACKAGE__->register_method(
2208 method => "check_title_hold",
2209 api_name => "open-ils.circ.title_hold.is_possible",
2211 desc => 'Determines if a hold were to be placed by a given user, ' .
2212 'whether or not said hold would have any potential copies to fulfill it.' .
2213 'The named paramaters of the second argument include: ' .
2214 'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
2215 'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' ,
2217 { desc => 'Authentication token', type => 'string'},
2218 { desc => 'Hash of named parameters', type => 'object'},
2221 desc => 'List of new message IDs (empty if none)',
2227 =head3 check_title_hold (token, hash)
2229 The named fields in the hash are:
2231 patronid - ID of the hold recipient (required)
2232 depth - hold range depth (default 0)
2233 pickup_lib - destination for hold, fallback value for selection_ou
2234 selection_ou - ID of org_unit establishing hard and soft hold boundary settings
2235 issuanceid - ID of the issuance to be held, required for Issuance level hold
2236 partid - ID of the monograph part to be held, required for monograph part level hold
2237 titleid - ID (BRN) of the title to be held, required for Title level hold
2238 volume_id - required for Volume level hold
2239 copy_id - required for Copy level hold
2240 mrid - required for Meta-record level hold
2241 hold_type - T, C (or R or F), I, V or M for Title, Copy, Issuance, Volume or Meta-record (default "T")
2243 All key/value pairs are passed on to do_possibility_checks.
2247 # FIXME: better params checking. what other params are required, if any?
2248 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
2249 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still
2250 # used in conditionals, where it may be undefined, causing a warning.
2251 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
2253 sub check_title_hold {
2254 my( $self, $client, $authtoken, $params ) = @_;
2255 my $e = new_editor(authtoken=>$authtoken);
2256 return $e->event unless $e->checkauth;
2258 my %params = %$params;
2259 my $depth = $params{depth} || 0;
2260 my $selection_ou = $params{selection_ou} || $params{pickup_lib};
2261 my $oargs = $params{oargs} || {};
2263 if($oargs->{events}) {
2264 @{$oargs->{events}} = grep { $e->allowed($_ . '.override', $e->requestor->ws_ou); } @{$oargs->{events}};
2268 my $patron = $e->retrieve_actor_user($params{patronid})
2269 or return $e->event;
2271 if( $e->requestor->id ne $patron->id ) {
2272 return $e->event unless
2273 $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
2276 return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
2278 my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
2279 or return $e->event;
2281 my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
2282 my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
2285 my $return_depth = $hard_boundary; # default depth to return on success
2286 if(defined $soft_boundary and $depth < $soft_boundary) {
2287 # work up the tree and as soon as we find a potential copy, use that depth
2288 # also, make sure we don't go past the hard boundary if it exists
2290 # our min boundary is the greater of user-specified boundary or hard boundary
2291 my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?
2292 $hard_boundary : $depth;
2294 my $depth = $soft_boundary;
2295 while($depth >= $min_depth) {
2296 $logger->info("performing hold possibility check with soft boundary $depth");
2297 @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
2299 $return_depth = $depth;
2304 } elsif(defined $hard_boundary and $depth < $hard_boundary) {
2305 # there is no soft boundary, enforce the hard boundary if it exists
2306 $logger->info("performing hold possibility check with hard boundary $hard_boundary");
2307 @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
2309 # no boundaries defined, fall back to user specifed boundary or no boundary
2310 $logger->info("performing hold possibility check with no boundary");
2311 @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
2314 my $place_unfillable = 0;
2315 $place_unfillable = 1 if $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
2320 "depth" => $return_depth,
2321 "local_avail" => $status[1]
2323 } elsif ($status[2]) {
2324 my $n = scalar @{$status[2]};
2325 return {"success" => 0, "last_event" => $status[2]->[$n - 1], "age_protected_copy" => $status[3], "place_unfillable" => $place_unfillable};
2327 return {"success" => 0, "age_protected_copy" => $status[3], "place_unfillable" => $place_unfillable};
2333 sub do_possibility_checks {
2334 my($e, $patron, $request_lib, $depth, %params) = @_;
2336 my $issuanceid = $params{issuanceid} || "";
2337 my $partid = $params{partid} || "";
2338 my $titleid = $params{titleid} || "";
2339 my $volid = $params{volume_id};
2340 my $copyid = $params{copy_id};
2341 my $mrid = $params{mrid} || "";
2342 my $pickup_lib = $params{pickup_lib};
2343 my $hold_type = $params{hold_type} || 'T';
2344 my $selection_ou = $params{selection_ou} || $pickup_lib;
2345 my $holdable_formats = $params{holdable_formats};
2346 my $oargs = $params{oargs} || {};
2353 if( $hold_type eq OILS_HOLD_TYPE_FORCE || $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_COPY ) {
2355 return $e->event unless $copy = $e->retrieve_asset_copy($copyid);
2356 return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
2357 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2359 return (1, 1, []) if( $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_FORCE);
2360 return verify_copy_for_hold(
2361 $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib, $oargs
2364 } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2366 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
2367 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2369 return _check_volume_hold_is_possible(
2370 $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2373 } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
2375 return _check_title_hold_is_possible(
2376 $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, undef, $oargs
2379 } elsif( $hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2381 return _check_issuance_hold_is_possible(
2382 $issuanceid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2385 } elsif( $hold_type eq OILS_HOLD_TYPE_MONOPART ) {
2387 return _check_monopart_hold_is_possible(
2388 $partid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2391 } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2393 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
2394 my @recs = map { $_->source } @$maps;
2396 for my $rec (@recs) {
2397 @status = _check_title_hold_is_possible(
2398 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $holdable_formats, $oargs
2404 # else { Unrecognized hold_type ! } # FIXME: return error? or 0?
2408 sub create_ranged_org_filter {
2409 my($e, $selection_ou, $depth) = @_;
2411 # find the orgs from which this hold may be fulfilled,
2412 # based on the selection_ou and depth
2414 my $top_org = $e->search_actor_org_unit([
2415 {parent_ou => undef},
2416 {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
2419 return () if $depth == $top_org->ou_type->depth;
2421 my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
2422 %org_filter = (circ_lib => []);
2423 push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
2425 $logger->info("hold org filter at depth $depth and selection_ou ".
2426 "$selection_ou created list of @{$org_filter{circ_lib}}");
2432 sub _check_title_hold_is_possible {
2433 my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $holdable_formats, $oargs ) = @_;
2435 my ($types, $formats, $lang);
2436 if (defined($holdable_formats)) {
2437 ($types, $formats, $lang) = split '-', $holdable_formats;
2440 my $e = new_editor();
2441 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2443 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2444 my $copies = $e->json_query(
2446 select => { acp => ['id', 'circ_lib'] },
2451 fkey => 'call_number',
2455 filter => { id => $titleid },
2463 ( $types ? (item_type => [split '', $types]) : () ),
2464 ( $formats ? (item_form => [split '', $formats]) : () ),
2465 ( $lang ? (item_lang => $lang) : () )
2470 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2471 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' },
2472 acpm => { field => 'target_copy', type => 'left' } # ignore part-linked copies
2476 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter },
2477 '+acpm' => { target_copy => undef } # ignore part-linked copies
2482 $logger->info("title possible found ".scalar(@$copies)." potential copies");
2486 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2487 "payload" => {"fail_part" => "no_ultimate_items"}
2492 # -----------------------------------------------------------------------
2493 # sort the copies into buckets based on their circ_lib proximity to
2494 # the patron's home_ou.
2495 # -----------------------------------------------------------------------
2497 my $home_org = $patron->home_ou;
2498 my $req_org = $request_lib->id;
2500 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2502 $prox_cache{$home_org} =
2503 $e->search_actor_org_unit_proximity({from_org => $home_org})
2504 unless $prox_cache{$home_org};
2505 my $home_prox = $prox_cache{$home_org};
2508 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2509 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2511 my @keys = sort { $a <=> $b } keys %buckets;
2514 if( $home_org ne $req_org ) {
2515 # -----------------------------------------------------------------------
2516 # shove the copies close to the request_lib into the primary buckets
2517 # directly before the farthest away copies. That way, they are not
2518 # given priority, but they are checked before the farthest copies.
2519 # -----------------------------------------------------------------------
2520 $prox_cache{$req_org} =
2521 $e->search_actor_org_unit_proximity({from_org => $req_org})
2522 unless $prox_cache{$req_org};
2523 my $req_prox = $prox_cache{$req_org};
2526 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2527 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2529 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2530 my $new_key = $highest_key - 0.5; # right before the farthest prox
2531 my @keys2 = sort { $a <=> $b } keys %buckets2;
2532 for my $key (@keys2) {
2533 last if $key >= $highest_key;
2534 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2538 @keys = sort { $a <=> $b } keys %buckets;
2543 my $age_protect_only = 0;
2544 OUTER: for my $key (@keys) {
2545 my @cps = @{$buckets{$key}};
2547 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2549 for my $copyid (@cps) {
2551 next if $seen{$copyid};
2552 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2553 my $copy = $e->retrieve_asset_copy($copyid);
2554 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2556 unless($title) { # grab the title if we don't already have it
2557 my $vol = $e->retrieve_asset_call_number(
2558 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2559 $title = $vol->record;
2562 @status = verify_copy_for_hold(
2563 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2565 $age_protect_only ||= $status[3];
2566 last OUTER if $status[0];
2570 $status[3] = $age_protect_only;
2574 sub _check_issuance_hold_is_possible {
2575 my( $issuanceid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2577 my $e = new_editor();
2578 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2580 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2581 my $copies = $e->json_query(
2583 select => { acp => ['id', 'circ_lib'] },
2589 filter => { issuance => $issuanceid }
2591 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2592 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2596 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2602 $logger->info("issuance possible found ".scalar(@$copies)." potential copies");
2606 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2607 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2612 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2613 "payload" => {"fail_part" => "no_ultimate_items"}
2621 # -----------------------------------------------------------------------
2622 # sort the copies into buckets based on their circ_lib proximity to
2623 # the patron's home_ou.
2624 # -----------------------------------------------------------------------
2626 my $home_org = $patron->home_ou;
2627 my $req_org = $request_lib->id;
2629 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2631 $prox_cache{$home_org} =
2632 $e->search_actor_org_unit_proximity({from_org => $home_org})
2633 unless $prox_cache{$home_org};
2634 my $home_prox = $prox_cache{$home_org};
2637 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2638 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2640 my @keys = sort { $a <=> $b } keys %buckets;
2643 if( $home_org ne $req_org ) {
2644 # -----------------------------------------------------------------------
2645 # shove the copies close to the request_lib into the primary buckets
2646 # directly before the farthest away copies. That way, they are not
2647 # given priority, but they are checked before the farthest copies.
2648 # -----------------------------------------------------------------------
2649 $prox_cache{$req_org} =
2650 $e->search_actor_org_unit_proximity({from_org => $req_org})
2651 unless $prox_cache{$req_org};
2652 my $req_prox = $prox_cache{$req_org};
2655 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2656 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2658 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2659 my $new_key = $highest_key - 0.5; # right before the farthest prox
2660 my @keys2 = sort { $a <=> $b } keys %buckets2;
2661 for my $key (@keys2) {
2662 last if $key >= $highest_key;
2663 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2667 @keys = sort { $a <=> $b } keys %buckets;
2672 my $age_protect_only = 0;
2673 OUTER: for my $key (@keys) {
2674 my @cps = @{$buckets{$key}};
2676 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2678 for my $copyid (@cps) {
2680 next if $seen{$copyid};
2681 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2682 my $copy = $e->retrieve_asset_copy($copyid);
2683 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2685 unless($title) { # grab the title if we don't already have it
2686 my $vol = $e->retrieve_asset_call_number(
2687 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2688 $title = $vol->record;
2691 @status = verify_copy_for_hold(
2692 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2694 $age_protect_only ||= $status[3];
2695 last OUTER if $status[0];
2700 if (!defined($empty_ok)) {
2701 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2702 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2705 return (1,0) if ($empty_ok);
2707 $status[3] = $age_protect_only;
2711 sub _check_monopart_hold_is_possible {
2712 my( $partid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2714 my $e = new_editor();
2715 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2717 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2718 my $copies = $e->json_query(
2720 select => { acp => ['id', 'circ_lib'] },
2724 field => 'target_copy',
2726 filter => { part => $partid }
2728 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2729 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2733 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2739 $logger->info("monopart possible found ".scalar(@$copies)." potential copies");
2743 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2744 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2749 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2750 "payload" => {"fail_part" => "no_ultimate_items"}
2758 # -----------------------------------------------------------------------
2759 # sort the copies into buckets based on their circ_lib proximity to
2760 # the patron's home_ou.
2761 # -----------------------------------------------------------------------
2763 my $home_org = $patron->home_ou;
2764 my $req_org = $request_lib->id;
2766 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2768 $prox_cache{$home_org} =
2769 $e->search_actor_org_unit_proximity({from_org => $home_org})
2770 unless $prox_cache{$home_org};
2771 my $home_prox = $prox_cache{$home_org};
2774 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2775 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2777 my @keys = sort { $a <=> $b } keys %buckets;
2780 if( $home_org ne $req_org ) {
2781 # -----------------------------------------------------------------------
2782 # shove the copies close to the request_lib into the primary buckets
2783 # directly before the farthest away copies. That way, they are not
2784 # given priority, but they are checked before the farthest copies.
2785 # -----------------------------------------------------------------------
2786 $prox_cache{$req_org} =
2787 $e->search_actor_org_unit_proximity({from_org => $req_org})
2788 unless $prox_cache{$req_org};
2789 my $req_prox = $prox_cache{$req_org};
2792 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2793 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2795 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2796 my $new_key = $highest_key - 0.5; # right before the farthest prox
2797 my @keys2 = sort { $a <=> $b } keys %buckets2;
2798 for my $key (@keys2) {
2799 last if $key >= $highest_key;
2800 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2804 @keys = sort { $a <=> $b } keys %buckets;
2809 my $age_protect_only = 0;
2810 OUTER: for my $key (@keys) {
2811 my @cps = @{$buckets{$key}};
2813 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2815 for my $copyid (@cps) {
2817 next if $seen{$copyid};
2818 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2819 my $copy = $e->retrieve_asset_copy($copyid);
2820 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2822 unless($title) { # grab the title if we don't already have it
2823 my $vol = $e->retrieve_asset_call_number(
2824 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2825 $title = $vol->record;
2828 @status = verify_copy_for_hold(
2829 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2831 $age_protect_only ||= $status[3];
2832 last OUTER if $status[0];
2837 if (!defined($empty_ok)) {
2838 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2839 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2842 return (1,0) if ($empty_ok);
2844 $status[3] = $age_protect_only;
2849 sub _check_volume_hold_is_possible {
2850 my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2851 my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
2852 my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
2853 $logger->info("checking possibility of volume hold for volume ".$vol->id);
2855 my $filter_copies = [];
2856 for my $copy (@$copies) {
2857 # ignore part-mapped copies for regular volume level holds
2858 push(@$filter_copies, $copy) unless
2859 new_editor->search_asset_copy_part_map({target_copy => $copy->id})->[0];
2861 $copies = $filter_copies;
2866 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2867 "payload" => {"fail_part" => "no_ultimate_items"}
2873 my $age_protect_only = 0;
2874 for my $copy ( @$copies ) {
2875 @status = verify_copy_for_hold(
2876 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs );
2877 $age_protect_only ||= $status[3];
2880 $status[3] = $age_protect_only;
2886 sub verify_copy_for_hold {
2887 my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs ) = @_;
2888 $oargs = {} unless defined $oargs;
2889 $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
2890 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2891 { patron => $patron,
2892 requestor => $requestor,
2895 title_descriptor => $title->fixed_fields, # this is fleshed into the title object
2896 pickup_lib => $pickup_lib,
2897 request_lib => $request_lib,
2899 show_event_list => 1
2904 my $permit_anyway = 0;
2905 foreach my $permit_event (@$permitted) {
2906 if (grep { $_ eq $permit_event->{textcode} } @{$oargs->{events}}) {
2911 $permitted = [] if $permit_anyway;
2913 my $age_protect_only = 0;
2914 if (@$permitted == 1 && @$permitted[0]->{textcode} eq 'ITEM_AGE_PROTECTED') {
2915 $age_protect_only = 1;
2919 (not scalar @$permitted), # true if permitted is an empty arrayref
2920 ( # XXX This test is of very dubious value; someone should figure
2921 # out what if anything is checking this value
2922 ($copy->circ_lib == $pickup_lib) and
2923 ($copy->status == OILS_COPY_STATUS_AVAILABLE)
2932 sub find_nearest_permitted_hold {
2935 my $editor = shift; # CStoreEditor object
2936 my $copy = shift; # copy to target
2937 my $user = shift; # staff
2938 my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
2940 my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
2942 my $bc = $copy->barcode;
2944 # find any existing holds that already target this copy
2945 my $old_holds = $editor->search_action_hold_request(
2946 { current_copy => $copy->id,
2947 cancel_time => undef,
2948 capture_time => undef
2952 my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
2954 $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
2955 " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
2957 my $fifo = $U->ou_ancestor_setting_value($user->ws_ou, 'circ.holds_fifo');
2959 # search for what should be the best holds for this copy to fulfill
2960 my $best_holds = $U->storagereq(
2961 "open-ils.storage.action.hold_request.nearest_hold.atomic",
2962 $user->ws_ou, $copy->id, 100, $hold_stall_interval, $fifo );
2964 # Add any pre-targeted holds to the list too? Unless they are already there, anyway.
2966 for my $holdid (@$old_holds) {
2967 next unless $holdid;
2968 push(@$best_holds, $holdid) unless ( grep { ''.$holdid eq ''.$_ } @$best_holds );
2972 unless(@$best_holds) {
2973 $logger->info("circulator: no suitable holds found for copy $bc");
2974 return (undef, $evt);
2980 # for each potential hold, we have to run the permit script
2981 # to make sure the hold is actually permitted.
2984 for my $holdid (@$best_holds) {
2985 next unless $holdid;
2986 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
2988 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
2989 my $reqr = $reqr_cache{$hold->requestor} || $editor->retrieve_actor_user($hold->requestor);
2990 my $rlib = $org_cache{$hold->request_lib} || $editor->retrieve_actor_org_unit($hold->request_lib);
2992 $reqr_cache{$hold->requestor} = $reqr;
2993 $org_cache{$hold->request_lib} = $rlib;
2995 # see if this hold is permitted
2996 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2997 { patron_id => $hold->usr,
3000 pickup_lib => $hold->pickup_lib,
3001 request_lib => $rlib,
3013 unless( $best_hold ) { # no "good" permitted holds were found
3015 $logger->info("circulator: no suitable holds found for copy $bc");
3016 return (undef, $evt);
3019 $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
3021 # indicate a permitted hold was found
3022 return $best_hold if $check_only;
3024 # we've found a permitted hold. we need to "grab" the copy
3025 # to prevent re-targeted holds (next part) from re-grabbing the copy
3026 $best_hold->current_copy($copy->id);
3027 $editor->update_action_hold_request($best_hold)
3028 or return (undef, $editor->event);
3033 # re-target any other holds that already target this copy
3034 for my $old_hold (@$old_holds) {
3035 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
3036 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
3037 $old_hold->id." after a better hold [".$best_hold->id."] was found");
3038 $old_hold->clear_current_copy;
3039 $old_hold->clear_prev_check_time;
3040 $editor->update_action_hold_request($old_hold)
3041 or return (undef, $editor->event);
3042 push(@retarget, $old_hold->id);
3045 return ($best_hold, undef, (@retarget) ? \@retarget : undef);
3053 __PACKAGE__->register_method(
3054 method => 'all_rec_holds',
3055 api_name => 'open-ils.circ.holds.retrieve_all_from_title',
3059 my( $self, $conn, $auth, $title_id, $args ) = @_;
3061 my $e = new_editor(authtoken=>$auth);
3062 $e->checkauth or return $e->event;
3063 $e->allowed('VIEW_HOLD') or return $e->event;
3066 $args->{fulfillment_time} = undef; # we don't want to see old fulfilled holds
3067 $args->{cancel_time} = undef;
3069 my $resp = { volume_holds => [], copy_holds => [], recall_holds => [], force_holds => [], metarecord_holds => [], part_holds => [], issuance_holds => [] };
3071 my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
3073 $resp->{metarecord_holds} = $e->search_action_hold_request(
3074 { hold_type => OILS_HOLD_TYPE_METARECORD,
3075 target => $mr_map->metarecord,
3081 $resp->{title_holds} = $e->search_action_hold_request(
3083 hold_type => OILS_HOLD_TYPE_TITLE,
3084 target => $title_id,
3088 my $parts = $e->search_biblio_monograph_part(
3094 $resp->{part_holds} = $e->search_action_hold_request(
3096 hold_type => OILS_HOLD_TYPE_MONOPART,
3102 my $subs = $e->search_serial_subscription(
3103 { record_entry => $title_id }, {idlist=>1});
3106 my $issuances = $e->search_serial_issuance(
3107 {subscription => $subs}, {idlist=>1}
3111 $resp->{issuance_holds} = $e->search_action_hold_request(
3113 hold_type => OILS_HOLD_TYPE_ISSUANCE,
3114 target => $issuances,
3121 my $vols = $e->search_asset_call_number(
3122 { record => $title_id, deleted => 'f' }, {idlist=>1});
3124 return $resp unless @$vols;
3126 $resp->{volume_holds} = $e->search_action_hold_request(
3128 hold_type => OILS_HOLD_TYPE_VOLUME,
3133 my $copies = $e->search_asset_copy(
3134 { call_number => $vols, deleted => 'f' }, {idlist=>1});
3136 return $resp unless @$copies;
3138 $resp->{copy_holds} = $e->search_action_hold_request(
3140 hold_type => OILS_HOLD_TYPE_COPY,
3145 $resp->{recall_holds} = $e->search_action_hold_request(
3147 hold_type => OILS_HOLD_TYPE_RECALL,
3152 $resp->{force_holds} = $e->search_action_hold_request(
3154 hold_type => OILS_HOLD_TYPE_FORCE,
3166 __PACKAGE__->register_method(
3167 method => 'uber_hold',
3169 api_name => 'open-ils.circ.hold.details.retrieve'
3173 my($self, $client, $auth, $hold_id, $args) = @_;
3174 my $e = new_editor(authtoken=>$auth);
3175 $e->checkauth or return $e->event;
3176 return uber_hold_impl($e, $hold_id, $args);
3179 __PACKAGE__->register_method(
3180 method => 'batch_uber_hold',
3183 api_name => 'open-ils.circ.hold.details.batch.retrieve'
3186 sub batch_uber_hold {
3187 my($self, $client, $auth, $hold_ids, $args) = @_;
3188 my $e = new_editor(authtoken=>$auth);
3189 $e->checkauth or return $e->event;
3190 $client->respond(uber_hold_impl($e, $_, $args)) for @$hold_ids;
3194 sub uber_hold_impl {
3195 my($e, $hold_id, $args) = @_;
3198 my $hold = $e->retrieve_action_hold_request(
3203 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
3206 ) or return $e->event;
3208 if($hold->usr->id ne $e->requestor->id) {
3209 # A user is allowed to see his/her own holds
3210 $e->allowed('VIEW_HOLD') or return $e->event;
3211 $hold->notes( # filter out any non-staff ("private") notes
3212 [ grep { !$U->is_true($_->staff) } @{$hold->notes} ] );
3215 # caller is asking for own hold, but may not have permission to view staff notes
3216 unless($e->allowed('VIEW_HOLD')) {
3217 $hold->notes( # filter out any staff notes
3218 [ grep { $U->is_true($_->staff) } @{$hold->notes} ] );
3222 my $user = $hold->usr;
3223 $hold->usr($user->id);
3226 my( $mvr, $volume, $copy, $issuance, $part, $bre ) = find_hold_mvr($e, $hold, $args->{suppress_mvr});
3228 flesh_hold_notices([$hold], $e) unless $args->{suppress_notices};
3229 flesh_hold_transits([$hold]) unless $args->{suppress_transits};
3231 my $details = retrieve_hold_queue_status_impl($e, $hold);
3236 ($copy ? (copy => $copy) : ()),
3237 ($volume ? (volume => $volume) : ()),
3238 ($issuance ? (issuance => $issuance) : ()),
3239 ($part ? (part => $part) : ()),
3240 ($args->{include_bre} ? (bre => $bre) : ()),
3241 ($args->{suppress_mvr} ? () : (mvr => $mvr)),
3245 unless($args->{suppress_patron_details}) {
3246 my $card = $e->retrieve_actor_card($user->card) or return $e->event;
3247 $resp->{patron_first} = $user->first_given_name,
3248 $resp->{patron_last} = $user->family_name,
3249 $resp->{patron_barcode} = $card->barcode,
3250 $resp->{patron_alias} = $user->alias,
3258 # -----------------------------------------------------
3259 # Returns the MVR object that represents what the
3261 # -----------------------------------------------------
3263 my( $e, $hold, $no_mvr ) = @_;
3271 if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
3272 my $mr = $e->retrieve_metabib_metarecord($hold->target)
3273 or return $e->event;
3274 $tid = $mr->master_record;
3276 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
3277 $tid = $hold->target;
3279 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
3280 $volume = $e->retrieve_asset_call_number($hold->target)
3281 or return $e->event;
3282 $tid = $volume->record;
3284 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
3285 $issuance = $e->retrieve_serial_issuance([
3287 {flesh => 1, flesh_fields => {siss => [ qw/subscription/ ]}}
3288 ]) or return $e->event;
3290 $tid = $issuance->subscription->record_entry;
3292 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_MONOPART ) {
3293 $part = $e->retrieve_biblio_monograph_part([
3295 ]) or return $e->event;
3297 $tid = $part->record;
3299 } 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 ) {
3300 $copy = $e->retrieve_asset_copy([
3302 {flesh => 1, flesh_fields => {acp => ['call_number']}}
3303 ]) or return $e->event;
3305 $volume = $copy->call_number;
3306 $tid = $volume->record;
3309 if(!$copy and ref $hold->current_copy ) {
3310 $copy = $hold->current_copy;
3311 $hold->current_copy($copy->id);
3314 if(!$volume and $copy) {
3315 $volume = $e->retrieve_asset_call_number($copy->call_number);
3318 # TODO return metarcord mvr for M holds
3319 my $title = $e->retrieve_biblio_record_entry($tid);
3320 return ( ($no_mvr) ? undef : $U->record_to_mvr($title), $volume, $copy, $issuance, $part, $title );
3323 __PACKAGE__->register_method(
3324 method => 'clear_shelf_cache',
3325 api_name => 'open-ils.circ.hold.clear_shelf.get_cache',
3329 Returns the holds processed with the given cache key
3334 sub clear_shelf_cache {
3335 my($self, $client, $auth, $cache_key, $chunk_size) = @_;
3336 my $e = new_editor(authtoken => $auth, xact => 1);
3337 return $e->die_event unless $e->checkauth and $e->allowed('VIEW_HOLD');
3340 my $hold_data = OpenSRF::Utils::Cache->new('global')->get_cache($cache_key);
3343 $logger->info("no hold data found in cache"); # XXX TODO return event
3349 foreach (keys %$hold_data) {
3350 $maximum += scalar(@{ $hold_data->{$_} });
3352 $client->respond({"maximum" => $maximum, "progress" => 0});
3354 for my $action (sort keys %$hold_data) {
3355 while (@{$hold_data->{$action}}) {
3356 my @hid_chunk = splice @{$hold_data->{$action}}, 0, $chunk_size;
3358 my $result_chunk = $e->json_query({
3360 "acp" => ["barcode"],
3362 first_given_name second_given_name family_name alias
3365 "acnp" => [{column => "label", alias => "prefix"}],
3366 "acns" => [{column => "label", alias => "suffix"}],
3374 "field" => "id", "fkey" => "current_copy",
3377 "field" => "id", "fkey" => "call_number",
3380 "field" => "id", "fkey" => "record"
3383 "field" => "id", "fkey" => "prefix"
3386 "field" => "id", "fkey" => "suffix"
3390 "acpl" => {"field" => "id", "fkey" => "location"}
3393 "au" => {"field" => "id", "fkey" => "usr"}
3396 "where" => {"+ahr" => {"id" => \@hid_chunk}}
3397 }, {"substream" => 1}) or return $e->die_event;
3401 +{"action" => $action, "hold_details" => $_}
3412 __PACKAGE__->register_method(
3413 method => 'clear_shelf_process',
3415 api_name => 'open-ils.circ.hold.clear_shelf.process',
3418 1. Find all holds that have expired on the holds shelf
3420 3. If a clear-shelf status is configured, put targeted copies into this status
3421 4. Divide copies into 3 groups: items to transit, items to reshelve, and items
3422 that are needed for holds. No subsequent action is taken on the holds
3423 or items after grouping.
3428 sub clear_shelf_process {
3429 my($self, $client, $auth, $org_id, $match_copy) = @_;
3431 my $e = new_editor(authtoken=>$auth, xact => 1);
3432 $e->checkauth or return $e->die_event;
3433 my $cache = OpenSRF::Utils::Cache->new('global');
3435 $org_id ||= $e->requestor->ws_ou;
3436 $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
3438 my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
3440 my @hold_ids = $self->method_lookup(
3441 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
3442 )->run($auth, $org_id, $match_copy);
3445 my @canceled_holds; # newly canceled holds
3446 my $chunk_size = 25; # chunked status updates
3448 for my $hold_id (@hold_ids) {
3450 $logger->info("Clear shelf processing hold $hold_id");
3452 my $hold = $e->retrieve_action_hold_request([
3455 flesh_fields => {ahr => ['current_copy']}
3459 if (!$hold->cancel_time) { # may be canceled but still on the holds shelf
3460 $hold->cancel_time('now');
3461 $hold->cancel_cause(2); # Hold Shelf expiration
3462 $e->update_action_hold_request($hold) or return $e->die_event;
3463 delete_hold_copy_maps($self, $e, $hold->id) and return $e->die_event;
3464 push(@canceled_holds, $hold_id);
3467 my $copy = $hold->current_copy;
3469 if($copy_status or $copy_status == 0) {
3470 # if a clear-shelf copy status is defined, update the copy
3471 $copy->status($copy_status);
3472 $copy->edit_date('now');
3473 $copy->editor($e->requestor->id);
3474 $e->update_asset_copy($copy) or return $e->die_event;
3477 push(@holds, $hold);
3478 $client->respond({maximum => scalar(@holds), progress => $counter}) if ( (++$counter % $chunk_size) == 0);
3489 for my $hold (@holds) {
3491 my $copy = $hold->current_copy;
3492 my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
3494 if($alt_hold and !$match_copy) {
3496 push(@{$cache_data{hold}}, $hold->id); # copy is needed for a hold
3498 } elsif($copy->circ_lib != $e->requestor->ws_ou) {
3500 push(@{$cache_data{transit}}, $hold->id); # copy needs to transit
3504 push(@{$cache_data{shelf}}, $hold->id); # copy needs to go back to the shelf
3508 my $cache_key = md5_hex(time . $$ . rand());
3509 $logger->info("clear_shelf_cache: storing under $cache_key");
3510 $cache->put_cache($cache_key, \%cache_data, 7200); # TODO: 2 hours. configurable?
3512 # tell the client we're done
3513 $client->respond_complete({cache_key => $cache_key});
3516 # fire off the hold cancelation trigger and wait for response so don't flood the service
3518 # refetch the holds to pick up the caclulated cancel_time,
3519 # which may be needed by Action/Trigger
3521 my $updated_holds = [];
3522 $updated_holds = $e->search_action_hold_request({id => \@canceled_holds}, {substream => 1}) if (@canceled_holds > 0);
3525 $U->create_events_for_hook(
3526 'hold_request.cancel.expire_holds_shelf',
3527 $_, $org_id, undef, undef, 1) for @$updated_holds;
3530 # tell the client we're done
3531 $client->respond_complete;
3535 __PACKAGE__->register_method(
3536 method => 'usr_hold_summary',
3537 api_name => 'open-ils.circ.holds.user_summary',
3539 Returns a summary of holds statuses for a given user
3543 sub usr_hold_summary {
3544 my($self, $conn, $auth, $user_id) = @_;
3546 my $e = new_editor(authtoken=>$auth);
3547 $e->checkauth or return $e->event;
3548 $e->allowed('VIEW_HOLD') or return $e->event;
3550 my $holds = $e->search_action_hold_request(
3553 fulfillment_time => undef,
3554 cancel_time => undef,
3558 my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
3559 $summary{_hold_status($e, $_)} += 1 for @$holds;
3565 __PACKAGE__->register_method(
3566 method => 'hold_has_copy_at',
3567 api_name => 'open-ils.circ.hold.has_copy_at',
3570 'Returns the ID of the found copy and name of the shelving location if there is ' .
3571 'an available copy at the specified org unit. Returns empty hash otherwise. ' .
3572 'The anticipated use for this method is to determine whether an item is ' .
3573 'available at the library where the user is placing the hold (or, alternatively, '.
3574 'at the pickup library) to encourage bypassing the hold placement and just ' .
3575 'checking out the item.' ,
3577 { desc => 'Authentication Token', type => 'string' },
3578 { desc => 'Method Arguments. Options include: hold_type, hold_target, org_unit. '
3579 . 'hold_type is the hold type code (T, V, C, M, ...). '
3580 . 'hold_target is the identifier of the hold target object. '
3581 . 'org_unit is org unit ID.',
3586 desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
3592 sub hold_has_copy_at {
3593 my($self, $conn, $auth, $args) = @_;
3595 my $e = new_editor(authtoken=>$auth);
3596 $e->checkauth or return $e->event;
3598 my $hold_type = $$args{hold_type};
3599 my $hold_target = $$args{hold_target};
3600 my $org_unit = $$args{org_unit};
3603 select => {acp => ['id'], acpl => ['name']},
3606 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
3607 ccs => {field => 'id', filter => { holdable => 't'}, fkey => 'status' }
3610 where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit, status => [0,7]}},
3614 if($hold_type eq 'C' or $hold_type eq 'F' or $hold_type eq 'R') {
3616 $query->{where}->{'+acp'}->{id} = $hold_target;
3618 } elsif($hold_type eq 'V') {
3620 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3622 } elsif($hold_type eq 'P') {
3624 $query->{from}->{acp}->{acpm} = {
3625 field => 'target_copy',
3627 filter => {part => $hold_target},
3630 } elsif($hold_type eq 'I') {
3632 $query->{from}->{acp}->{sitem} = {
3635 filter => {issuance => $hold_target},
3638 } elsif($hold_type eq 'T') {
3640 $query->{from}->{acp}->{acn} = {
3642 fkey => 'call_number',
3646 filter => {id => $hold_target},
3654 $query->{from}->{acp}->{acn} = {
3656 fkey => 'call_number',
3665 filter => {metarecord => $hold_target},
3673 my $res = $e->json_query($query)->[0] or return {};
3674 return {copy => $res->{id}, location => $res->{name}} if $res;
3678 # returns true if the user already has an item checked out
3679 # that could be used to fulfill the requested hold.
3680 sub hold_item_is_checked_out {
3681 my($e, $user_id, $hold_type, $hold_target) = @_;
3684 select => {acp => ['id']},
3685 from => {acp => {}},
3689 in => { # copies for circs the user has checked out
3690 select => {circ => ['target_copy']},
3694 checkin_time => undef,
3696 {stop_fines => ["MAXFINES","LONGOVERDUE"]},
3697 {stop_fines => undef}
3707 if($hold_type eq 'C' || $hold_type eq 'R' || $hold_type eq 'F') {
3709 $query->{where}->{'+acp'}->{id}->{in}->{where}->{'target_copy'} = $hold_target;
3711 } elsif($hold_type eq 'V') {
3713 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3715 } elsif($hold_type eq 'P') {
3717 $query->{from}->{acp}->{acpm} = {
3718 field => 'target_copy',
3720 filter => {part => $hold_target},
3723 } elsif($hold_type eq 'I') {
3725 $query->{from}->{acp}->{sitem} = {
3728 filter => {issuance => $hold_target},
3731 } elsif($hold_type eq 'T') {
3733 $query->{from}->{acp}->{acn} = {
3735 fkey => 'call_number',
3739 filter => {id => $hold_target},
3747 $query->{from}->{acp}->{acn} = {
3749 fkey => 'call_number',
3758 filter => {metarecord => $hold_target},
3766 return $e->json_query($query)->[0];
3769 __PACKAGE__->register_method(
3770 method => 'change_hold_title',
3771 api_name => 'open-ils.circ.hold.change_title',
3774 Updates all title level holds targeting the specified bibs to point a new bib./,
3776 { desc => 'Authentication Token', type => 'string' },
3777 { desc => 'New Target Bib Id', type => 'number' },
3778 { desc => 'Old Target Bib Ids', type => 'array' },
3780 return => { desc => '1 on success' }
3784 __PACKAGE__->register_method(
3785 method => 'change_hold_title_for_specific_holds',
3786 api_name => 'open-ils.circ.hold.change_title.specific_holds',
3789 Updates specified holds to target new bib./,
3791 { desc => 'Authentication Token', type => 'string' },
3792 { desc => 'New Target Bib Id', type => 'number' },
3793 { desc => 'Holds Ids for holds to update', type => 'array' },
3795 return => { desc => '1 on success' }
3800 sub change_hold_title {
3801 my( $self, $client, $auth, $new_bib_id, $bib_ids ) = @_;
3803 my $e = new_editor(authtoken=>$auth, xact=>1);
3804 return $e->die_event unless $e->checkauth;
3806 my $holds = $e->search_action_hold_request(
3809 cancel_time => undef,
3810 fulfillment_time => undef,
3816 flesh_fields => { ahr => ['usr'] }
3822 for my $hold (@$holds) {
3823 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3824 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3825 $hold->target( $new_bib_id );
3826 $e->update_action_hold_request($hold) or return $e->die_event;
3831 _reset_hold($self, $e->requestor, $_) for @$holds;
3836 sub change_hold_title_for_specific_holds {
3837 my( $self, $client, $auth, $new_bib_id, $hold_ids ) = @_;
3839 my $e = new_editor(authtoken=>$auth, xact=>1);
3840 return $e->die_event unless $e->checkauth;
3842 my $holds = $e->search_action_hold_request(
3845 cancel_time => undef,
3846 fulfillment_time => undef,
3852 flesh_fields => { ahr => ['usr'] }
3858 for my $hold (@$holds) {
3859 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3860 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3861 $hold->target( $new_bib_id );
3862 $e->update_action_hold_request($hold) or return $e->die_event;
3867 _reset_hold($self, $e->requestor, $_) for @$holds;
3872 __PACKAGE__->register_method(
3873 method => 'rec_hold_count',
3874 api_name => 'open-ils.circ.bre.holds.count',
3876 desc => q/Returns the total number of holds that target the
3877 selected bib record or its associated copies and call_numbers/,
3879 { desc => 'Bib ID', type => 'number' },
3881 return => {desc => 'Hold count', type => 'number'}
3885 __PACKAGE__->register_method(
3886 method => 'rec_hold_count',
3887 api_name => 'open-ils.circ.mmr.holds.count',
3889 desc => q/Returns the total number of holds that target the
3890 selected metarecord or its associated copies, call_numbers, and bib records/,
3892 { desc => 'Metarecord ID', type => 'number' },
3894 return => {desc => 'Hold count', type => 'number'}
3898 # XXX Need to add type I (and, soon, type P) holds to these counts
3899 sub rec_hold_count {
3900 my($self, $conn, $target_id) = @_;
3907 filter => {metarecord => $target_id}
3914 filter => { id => $target_id },
3919 if($self->api_name =~ /mmr/) {
3920 delete $bre_join->{bre}->{filter};
3921 $bre_join->{bre}->{join} = $mmr_join;
3927 fkey => 'call_number',
3933 select => {ahr => [{column => 'id', transform => 'count', alias => 'count'}]},
3937 cancel_time => undef,
3938 fulfillment_time => undef,
3942 hold_type => [qw/C F R/],
3945 select => {acp => ['id']},
3946 from => { acp => $cn_join }
3956 select => {acn => ['id']},
3957 from => {acn => $bre_join}
3965 target => $target_id
3973 if($self->api_name =~ /mmr/) {
3974 $query->{where}->{'+ahr'}->{'-or'}->[2] = {
3979 select => {bre => ['id']},
3980 from => {bre => $mmr_join}
3986 $query->{where}->{'+ahr'}->{'-or'}->[3] = {
3989 target => $target_id
3995 return new_editor()->json_query($query)->[0]->{count};
3998 # A helper function to calculate a hold's expiration time at a given
3999 # org_unit. Takes the org_unit as an argument and returns either the
4000 # hold expire time as an ISO8601 string or undef if there is no hold
4001 # expiration interval set for the subject ou.
4002 sub calculate_expire_time
4005 my $interval = $U->ou_ancestor_setting_value($ou, OILS_SETTING_HOLD_EXPIRE);
4007 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
4008 return $U->epoch2ISO8601($date->epoch);