1 # ---------------------------------------------------------------
2 # Copyright (C) 2005 Georgia Public Library Service
3 # Bill Erickson <highfalutin@gmail.com>
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 # ---------------------------------------------------------------
17 package OpenILS::Application::Circ::Holds;
18 use base qw/OpenILS::Application/;
19 use strict; use warnings;
20 use OpenILS::Application::AppUtils;
23 use OpenSRF::EX qw(:try);
27 use OpenSRF::Utils::Logger qw(:logger);
28 use OpenILS::Utils::CStoreEditor q/:funcs/;
29 use OpenILS::Utils::PermitHold;
30 use OpenSRF::Utils::SettingsClient;
31 use OpenILS::Const qw/:const/;
32 use OpenILS::Application::Circ::Transit;
33 use OpenILS::Application::Actor::Friends;
35 use DateTime::Format::ISO8601;
36 use OpenSRF::Utils qw/:datetime/;
37 use Digest::MD5 qw(md5_hex);
38 use OpenSRF::Utils::Cache;
39 my $apputils = "OpenILS::Application::AppUtils";
42 __PACKAGE__->register_method(
43 method => "test_and_create_hold_batch",
44 api_name => "open-ils.circ.holds.test_and_create.batch",
47 desc => q/This is for batch creating a set of holds where every field is identical except for the targets./,
49 { desc => 'Authentication token', type => 'string' },
50 { desc => 'Hash of named parameters. Same as for open-ils.circ.title_hold.is_possible, though the pertinent target field is automatically populated based on the hold_type and the specified list of targets.', type => 'object'},
51 { desc => 'Array of target ids', type => 'array' }
54 desc => 'Array of hold ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
59 __PACKAGE__->register_method(
60 method => "test_and_create_hold_batch",
61 api_name => "open-ils.circ.holds.test_and_create.batch.override",
64 desc => '@see open-ils.circ.holds.test_and_create.batch',
69 sub test_and_create_hold_batch {
70 my( $self, $conn, $auth, $params, $target_list, $oargs ) = @_;
72 my $override = 1 if $self->api_name =~ /override/;
73 $oargs = { all => 1 } unless defined $oargs;
75 my $e = new_editor(authtoken=>$auth);
76 return $e->die_event unless $e->checkauth;
77 $$params{'requestor'} = $e->requestor->id;
80 if ($$params{'hold_type'} eq 'T') { $target_field = 'titleid'; }
81 elsif ($$params{'hold_type'} eq 'C') { $target_field = 'copy_id'; }
82 elsif ($$params{'hold_type'} eq 'R') { $target_field = 'copy_id'; }
83 elsif ($$params{'hold_type'} eq 'F') { $target_field = 'copy_id'; }
84 elsif ($$params{'hold_type'} eq 'I') { $target_field = 'issuanceid'; }
85 elsif ($$params{'hold_type'} eq 'V') { $target_field = 'volume_id'; }
86 elsif ($$params{'hold_type'} eq 'M') { $target_field = 'mrid'; }
87 elsif ($$params{'hold_type'} eq 'P') { $target_field = 'partid'; }
88 else { return undef; }
90 foreach (@$target_list) {
91 $$params{$target_field} = $_;
93 ($res) = $self->method_lookup(
94 'open-ils.circ.title_hold.is_possible')->run($auth, $params, $override ? $oargs : {});
95 if ($res->{'success'} == 1) {
96 my $ahr = construct_hold_request_object($params);
97 my ($res2) = $self->method_lookup(
99 ? 'open-ils.circ.holds.create.override'
100 : 'open-ils.circ.holds.create'
101 )->run($auth, $ahr, $oargs);
103 'target' => $$params{$target_field},
106 $conn->respond($res2);
109 'target' => $$params{$target_field},
112 $conn->respond($res);
118 sub construct_hold_request_object {
121 my $ahr = Fieldmapper::action::hold_request->new;
124 foreach my $field (keys %{ $params }) {
125 if ($field eq 'depth') { $ahr->selection_depth($$params{$field}); }
126 elsif ($field eq 'patronid') {
127 $ahr->usr($$params{$field}); }
128 elsif ($field eq 'titleid') { $ahr->target($$params{$field}); }
129 elsif ($field eq 'copy_id') { $ahr->target($$params{$field}); }
130 elsif ($field eq 'issuanceid') { $ahr->target($$params{$field}); }
131 elsif ($field eq 'volume_id') { $ahr->target($$params{$field}); }
132 elsif ($field eq 'mrid') { $ahr->target($$params{$field}); }
133 elsif ($field eq 'partid') { $ahr->target($$params{$field}); }
135 $ahr->$field($$params{$field});
141 __PACKAGE__->register_method(
142 method => "create_hold_batch",
143 api_name => "open-ils.circ.holds.create.batch",
146 desc => q/@see open-ils.circ.holds.create.batch/,
148 { desc => 'Authentication token', type => 'string' },
149 { desc => 'Array of hold objects', type => 'array' }
152 desc => 'Array of hold ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
157 __PACKAGE__->register_method(
158 method => "create_hold_batch",
159 api_name => "open-ils.circ.holds.create.override.batch",
162 desc => '@see open-ils.circ.holds.create.batch',
167 sub create_hold_batch {
168 my( $self, $conn, $auth, $hold_list, $oargs ) = @_;
169 (my $method = $self->api_name) =~ s/\.batch//og;
170 foreach (@$hold_list) {
171 my ($res) = $self->method_lookup($method)->run($auth, $_, $oargs);
172 $conn->respond($res);
178 __PACKAGE__->register_method(
179 method => "create_hold",
180 api_name => "open-ils.circ.holds.create",
182 desc => "Create a new hold for an item. From a permissions perspective, " .
183 "the login session is used as the 'requestor' of the hold. " .
184 "The hold recipient is determined by the 'usr' setting within the hold object. " .
185 'First we verify the requestor has holds request permissions. ' .
186 'Then we verify that the recipient is allowed to make the given hold. ' .
187 'If not, we see if the requestor has "override" capabilities. If not, ' .
188 'a permission exception is returned. If permissions allow, we cycle ' .
189 'through the set of holds objects and create. ' .
190 'If the recipient does not have permission to place multiple holds ' .
191 'on a single title and said operation is attempted, a permission ' .
192 'exception is returned',
194 { desc => 'Authentication token', type => 'string' },
195 { desc => 'Hold object for hold to be created',
196 type => 'object', class => 'ahr' }
199 desc => 'New ahr ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
204 __PACKAGE__->register_method(
205 method => "create_hold",
206 api_name => "open-ils.circ.holds.create.override",
207 notes => '@see open-ils.circ.holds.create',
209 desc => "If the recipient is not allowed to receive the requested hold, " .
210 "call this method to attempt the override",
212 { desc => 'Authentication token', type => 'string' },
214 desc => 'Hold object for hold to be created',
215 type => 'object', class => 'ahr'
219 desc => 'New hold (ahr) ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
225 my( $self, $conn, $auth, $hold, $oargs ) = @_;
226 return -1 unless $hold;
227 my $e = new_editor(authtoken=>$auth, xact=>1);
228 return $e->die_event unless $e->checkauth;
230 my $override = 1 if $self->api_name =~ /override/;
231 $oargs = { all => 1 } unless defined $oargs;
235 my $requestor = $e->requestor;
236 my $recipient = $requestor;
238 if( $requestor->id ne $hold->usr ) {
239 # Make sure the requestor is allowed to place holds for
240 # the recipient if they are not the same people
241 $recipient = $e->retrieve_actor_user($hold->usr) or return $e->die_event;
242 $e->allowed('REQUEST_HOLDS', $recipient->home_ou) or return $e->die_event;
245 # If the related org setting tells us to, block if patron privs have expired
246 my $expire_setting = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_BLOCK_HOLD_FOR_EXPIRED_PATRON);
247 if ($expire_setting) {
248 my $expire = DateTime::Format::ISO8601->new->parse_datetime(
249 cleanse_ISO8601($recipient->expire_date));
251 push( @events, OpenILS::Event->new(
252 'PATRON_ACCOUNT_EXPIRED',
253 "payload" => {"fail_part" => "actor.usr.privs_expired"}
254 )) if( CORE::time > $expire->epoch ) ;
257 # Now make sure the recipient is allowed to receive the specified hold
258 my $porg = $recipient->home_ou;
259 my $rid = $e->requestor->id;
260 my $t = $hold->hold_type;
262 # See if a duplicate hold already exists
264 usr => $recipient->id,
266 fulfillment_time => undef,
267 target => $hold->target,
268 cancel_time => undef,
271 $sargs->{holdable_formats} = $hold->holdable_formats if $t eq 'M';
273 my $existing = $e->search_action_hold_request($sargs);
274 push( @events, OpenILS::Event->new('HOLD_EXISTS')) if @$existing;
276 my $checked_out = hold_item_is_checked_out($e, $recipient->id, $hold->hold_type, $hold->target);
277 push( @events, OpenILS::Event->new('HOLD_ITEM_CHECKED_OUT')) if $checked_out;
279 if ( $t eq OILS_HOLD_TYPE_METARECORD ) {
280 return $e->die_event unless $e->allowed('MR_HOLDS', $porg);
281 } elsif ( $t eq OILS_HOLD_TYPE_TITLE ) {
282 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
283 } elsif ( $t eq OILS_HOLD_TYPE_VOLUME ) {
284 return $e->die_event unless $e->allowed('VOLUME_HOLDS', $porg);
285 } elsif ( $t eq OILS_HOLD_TYPE_MONOPART ) {
286 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
287 } elsif ( $t eq OILS_HOLD_TYPE_ISSUANCE ) {
288 return $e->die_event unless $e->allowed('ISSUANCE_HOLDS', $porg);
289 } elsif ( $t eq OILS_HOLD_TYPE_COPY ) {
290 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
291 } elsif ( $t eq OILS_HOLD_TYPE_FORCE || $t eq OILS_HOLD_TYPE_RECALL ) {
292 my $copy = $e->retrieve_asset_copy($hold->target)
293 or return $e->die_event;
294 if ( $t eq OILS_HOLD_TYPE_FORCE ) {
295 return $e->die_event unless $e->allowed('COPY_HOLDS_FORCE', $copy->circ_lib);
296 } elsif ( $t eq OILS_HOLD_TYPE_RECALL ) {
297 return $e->die_event unless $e->allowed('COPY_HOLDS_RECALL', $copy->circ_lib);
306 for my $evt (@events) {
308 my $name = $evt->{textcode};
309 if($oargs->{all} || grep { $_ eq $name } @{$oargs->{events}}) {
310 return $e->die_event unless $e->allowed("$name.override", $porg);
318 # Check for hold expiration in the past, and set it to empty string.
319 $hold->expire_time(undef) if ($hold->expire_time && $U->datecmp($hold->expire_time) == -1);
321 # set the configured expire time
322 unless($hold->expire_time) {
323 $hold->expire_time(calculate_expire_time($recipient->home_ou));
326 $hold->requestor($e->requestor->id);
327 $hold->request_lib($e->requestor->ws_ou);
328 $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
329 $hold = $e->create_action_hold_request($hold) or return $e->die_event;
333 $conn->respond_complete($hold->id);
336 'open-ils.storage.action.hold_request.copy_targeter',
337 undef, $hold->id ) unless $U->is_true($hold->frozen);
342 # makes sure that a user has permission to place the type of requested hold
343 # returns the Perm exception if not allowed, returns undef if all is well
344 sub _check_holds_perm {
345 my($type, $user_id, $org_id) = @_;
349 $evt = $apputils->check_perms($user_id, $org_id, "MR_HOLDS" );
350 } elsif ($type eq "T") {
351 $evt = $apputils->check_perms($user_id, $org_id, "TITLE_HOLDS" );
352 } elsif($type eq "V") {
353 $evt = $apputils->check_perms($user_id, $org_id, "VOLUME_HOLDS");
354 } elsif($type eq "C") {
355 $evt = $apputils->check_perms($user_id, $org_id, "COPY_HOLDS" );
362 # tests if the given user is allowed to place holds on another's behalf
363 sub _check_request_holds_perm {
366 if (my $evt = $apputils->check_perms(
367 $user_id, $org_id, "REQUEST_HOLDS")) {
372 my $ses_is_req_note = 'The login session is the requestor. If the requestor is different from the user, ' .
373 'then the requestor must have VIEW_HOLD permissions';
375 __PACKAGE__->register_method(
376 method => "retrieve_holds_by_id",
377 api_name => "open-ils.circ.holds.retrieve_by_id",
379 desc => "Retrieve the hold, with hold transits attached, for the specified ID. $ses_is_req_note",
381 { desc => 'Authentication token', type => 'string' },
382 { desc => 'Hold ID', type => 'number' }
385 desc => 'Hold object with transits attached, event on error',
391 sub retrieve_holds_by_id {
392 my($self, $client, $auth, $hold_id) = @_;
393 my $e = new_editor(authtoken=>$auth);
394 $e->checkauth or return $e->event;
395 $e->allowed('VIEW_HOLD') or return $e->event;
397 my $holds = $e->search_action_hold_request(
399 { id => $hold_id , fulfillment_time => undef },
401 order_by => { ahr => "request_time" },
403 flesh_fields => {ahr => ['notes']}
408 flesh_hold_transits($holds);
409 flesh_hold_notices($holds, $e);
414 __PACKAGE__->register_method(
415 method => "retrieve_holds",
416 api_name => "open-ils.circ.holds.retrieve",
418 desc => "Retrieves all the holds, with hold transits attached, for the specified user. $ses_is_req_note",
420 { desc => 'Authentication token', type => 'string' },
421 { desc => 'User ID', type => 'integer' },
422 { desc => 'Available Only', type => 'boolean' }
425 desc => 'list of holds, event on error',
430 __PACKAGE__->register_method(
431 method => "retrieve_holds",
432 api_name => "open-ils.circ.holds.id_list.retrieve",
435 desc => "Retrieves all the hold IDs, for the specified user. $ses_is_req_note",
437 { desc => 'Authentication token', type => 'string' },
438 { desc => 'User ID', type => 'integer' },
439 { desc => 'Available Only', type => 'boolean' }
442 desc => 'list of holds, event on error',
447 __PACKAGE__->register_method(
448 method => "retrieve_holds",
449 api_name => "open-ils.circ.holds.canceled.retrieve",
452 desc => "Retrieves all the cancelled holds for the specified user. $ses_is_req_note",
454 { desc => 'Authentication token', type => 'string' },
455 { desc => 'User ID', type => 'integer' }
458 desc => 'list of holds, event on error',
463 __PACKAGE__->register_method(
464 method => "retrieve_holds",
465 api_name => "open-ils.circ.holds.canceled.id_list.retrieve",
468 desc => "Retrieves list of cancelled hold IDs for the specified user. $ses_is_req_note",
470 { desc => 'Authentication token', type => 'string' },
471 { desc => 'User ID', type => 'integer' }
474 desc => 'list of hold IDs, event on error',
481 my ($self, $client, $auth, $user_id, $available) = @_;
483 my $e = new_editor(authtoken=>$auth);
484 return $e->event unless $e->checkauth;
485 $user_id = $e->requestor->id unless defined $user_id;
487 my $notes_filter = {staff => 'f'};
488 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
489 unless($user_id == $e->requestor->id) {
490 if($e->allowed('VIEW_HOLD', $user->home_ou)) {
491 $notes_filter = {staff => 't'}
493 my $allowed = OpenILS::Application::Actor::Friends->friend_perm_allowed(
494 $e, $user_id, $e->requestor->id, 'hold.view');
495 return $e->event unless $allowed;
498 # staff member looking at his/her own holds can see staff and non-staff notes
499 $notes_filter = {} if $e->allowed('VIEW_HOLD', $user->home_ou);
503 select => {ahr => ['id']},
505 where => {usr => $user_id, fulfillment_time => undef}
508 if($self->api_name =~ /canceled/) {
510 # Fetch the canceled holds
511 # order cancelled holds by cancel time, most recent first
513 $holds_query->{order_by} = [{class => 'ahr', field => 'cancel_time', direction => 'desc'}];
516 my $cancel_count = $U->ou_ancestor_setting_value(
517 $e->requestor->ws_ou, 'circ.holds.canceled.display_count', $e);
519 unless($cancel_count) {
520 $cancel_age = $U->ou_ancestor_setting_value(
521 $e->requestor->ws_ou, 'circ.holds.canceled.display_age', $e);
523 # if no settings are defined, default to last 10 cancelled holds
524 $cancel_count = 10 unless $cancel_age;
527 if($cancel_count) { # limit by count
529 $holds_query->{where}->{cancel_time} = {'!=' => undef};
530 $holds_query->{limit} = $cancel_count;
532 } elsif($cancel_age) { # limit by age
534 # find all of the canceled holds that were canceled within the configured time frame
535 my $date = DateTime->now->subtract(seconds => OpenSRF::Utils::interval_to_seconds($cancel_age));
536 $date = $U->epoch2ISO8601($date->epoch);
537 $holds_query->{where}->{cancel_time} = {'>=' => $date};
542 # order non-cancelled holds by ready-for-pickup, then active, followed by suspended
543 # "compare" sorts false values to the front. testing pickup_lib != current_shelf_lib
544 # will sort by pl = csl > pl != csl > followed by csl is null;
545 $holds_query->{order_by} = [
547 field => 'pickup_lib',
548 compare => {'!=' => {'+ahr' => 'current_shelf_lib'}}},
549 {class => 'ahr', field => 'shelf_time'},
550 {class => 'ahr', field => 'frozen'},
551 {class => 'ahr', field => 'request_time'}
554 $holds_query->{where}->{cancel_time} = undef;
556 $holds_query->{where}->{shelf_time} = {'!=' => undef};
558 $holds_query->{where}->{pickup_lib} = {'=' => 'current_shelf_lib'};
562 my $hold_ids = $e->json_query($holds_query);
563 $hold_ids = [ map { $_->{id} } @$hold_ids ];
565 return $hold_ids if $self->api_name =~ /id_list/;
568 for my $hold_id ( @$hold_ids ) {
570 my $hold = $e->retrieve_action_hold_request($hold_id);
571 $hold->notes($e->search_action_hold_request_note({hold => $hold_id, %$notes_filter}));
574 $e->search_action_hold_transit_copy([
576 {order_by => {ahtc => 'source_send_time desc'}, limit => 1}])->[0]
586 __PACKAGE__->register_method(
587 method => 'user_hold_count',
588 api_name => 'open-ils.circ.hold.user.count'
591 sub user_hold_count {
592 my ( $self, $conn, $auth, $userid ) = @_;
593 my $e = new_editor( authtoken => $auth );
594 return $e->event unless $e->checkauth;
595 my $patron = $e->retrieve_actor_user($userid)
597 return $e->event unless $e->allowed( 'VIEW_HOLD', $patron->home_ou );
598 return __user_hold_count( $self, $e, $userid );
601 sub __user_hold_count {
602 my ( $self, $e, $userid ) = @_;
603 my $holds = $e->search_action_hold_request(
606 fulfillment_time => undef,
607 cancel_time => undef,
612 return scalar(@$holds);
616 __PACKAGE__->register_method(
617 method => "retrieve_holds_by_pickup_lib",
618 api_name => "open-ils.circ.holds.retrieve_by_pickup_lib",
620 "Retrieves all the holds, with hold transits attached, for the specified pickup_ou id."
623 __PACKAGE__->register_method(
624 method => "retrieve_holds_by_pickup_lib",
625 api_name => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
626 notes => "Retrieves all the hold ids for the specified pickup_ou id. "
629 sub retrieve_holds_by_pickup_lib {
630 my ($self, $client, $login_session, $ou_id) = @_;
632 #FIXME -- put an appropriate permission check here
633 #my( $user, $target, $evt ) = $apputils->checkses_requestor(
634 # $login_session, $user_id, 'VIEW_HOLD' );
635 #return $evt if $evt;
637 my $holds = $apputils->simplereq(
639 "open-ils.cstore.direct.action.hold_request.search.atomic",
641 pickup_lib => $ou_id ,
642 fulfillment_time => undef,
645 { order_by => { ahr => "request_time" } }
648 if ( ! $self->api_name =~ /id_list/ ) {
649 flesh_hold_transits($holds);
653 return [ map { $_->id } @$holds ];
657 __PACKAGE__->register_method(
658 method => "uncancel_hold",
659 api_name => "open-ils.circ.hold.uncancel"
663 my($self, $client, $auth, $hold_id) = @_;
664 my $e = new_editor(authtoken=>$auth, xact=>1);
665 return $e->die_event unless $e->checkauth;
667 my $hold = $e->retrieve_action_hold_request($hold_id)
668 or return $e->die_event;
669 return $e->die_event unless $e->allowed('CANCEL_HOLDS', $hold->request_lib);
671 if ($hold->fulfillment_time) {
675 unless ($hold->cancel_time) {
680 # if configured to reset the request time, also reset the expire time
681 if($U->ou_ancestor_setting_value(
682 $hold->request_lib, 'circ.holds.uncancel.reset_request_time', $e)) {
684 $hold->request_time('now');
685 $hold->expire_time(calculate_expire_time($hold->request_lib));
688 $hold->clear_cancel_time;
689 $hold->clear_cancel_cause;
690 $hold->clear_cancel_note;
691 $hold->clear_shelf_time;
692 $hold->clear_current_copy;
693 $hold->clear_capture_time;
694 $hold->clear_prev_check_time;
695 $hold->clear_shelf_expire_time;
696 $hold->clear_current_shelf_lib;
698 $e->update_action_hold_request($hold) or return $e->die_event;
701 $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
707 __PACKAGE__->register_method(
708 method => "cancel_hold",
709 api_name => "open-ils.circ.hold.cancel",
711 desc => 'Cancels the specified hold. The login session is the requestor. If the requestor is different from the usr field ' .
712 'on the hold, the requestor must have CANCEL_HOLDS permissions. The hold may be either the hold object or the hold id',
714 {desc => 'Authentication token', type => 'string'},
715 {desc => 'Hold ID', type => 'number'},
716 {desc => 'Cause of Cancellation', type => 'string'},
717 {desc => 'Note', type => 'string'}
720 desc => '1 on success, event on error'
726 my($self, $client, $auth, $holdid, $cause, $note) = @_;
728 my $e = new_editor(authtoken=>$auth, xact=>1);
729 return $e->die_event unless $e->checkauth;
731 my $hold = $e->retrieve_action_hold_request($holdid)
732 or return $e->die_event;
734 if( $e->requestor->id ne $hold->usr ) {
735 return $e->die_event unless $e->allowed('CANCEL_HOLDS');
738 if ($hold->cancel_time) {
743 # If the hold is captured, reset the copy status
744 if( $hold->capture_time and $hold->current_copy ) {
746 my $copy = $e->retrieve_asset_copy($hold->current_copy)
747 or return $e->die_event;
749 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
750 $logger->info("canceling hold $holdid whose item is on the holds shelf");
751 # $logger->info("setting copy to status 'reshelving' on hold cancel");
752 # $copy->status(OILS_COPY_STATUS_RESHELVING);
753 # $copy->editor($e->requestor->id);
754 # $copy->edit_date('now');
755 # $e->update_asset_copy($copy) or return $e->event;
757 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
760 $logger->warn("! canceling hold [$hid] that is in transit");
761 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
764 my $trans = $e->retrieve_action_transit_copy($transid);
765 # Leave the transit alive, but set the copy status to
766 # reshelving so it will be properly reshelved when it gets back home
768 $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
769 $e->update_action_transit_copy($trans) or return $e->die_event;
775 $hold->cancel_time('now');
776 $hold->cancel_cause($cause);
777 $hold->cancel_note($note);
778 $e->update_action_hold_request($hold)
779 or return $e->die_event;
781 delete_hold_copy_maps($self, $e, $hold->id);
785 # re-fetch the hold to pick up the real cancel_time (not "now") for A/T
787 $hold = $e->retrieve_action_hold_request($hold->id) or return $e->die_event;
790 if ($e->requestor->id == $hold->usr) {
791 $U->create_events_for_hook('hold_request.cancel.patron', $hold, $hold->pickup_lib);
793 $U->create_events_for_hook('hold_request.cancel.staff', $hold, $hold->pickup_lib);
799 sub delete_hold_copy_maps {
804 my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
806 $editor->delete_action_hold_copy_map($_)
807 or return $editor->event;
813 my $update_hold_desc = 'The login session is the requestor. ' .
814 'If the requestor is different from the usr field on the hold, ' .
815 'the requestor must have UPDATE_HOLDS permissions. ' .
816 'If supplying a hash of hold data, "id" must be included. ' .
817 'The hash is ignored if a hold object is supplied, ' .
818 'so you should supply only one kind of hold data argument.' ;
820 __PACKAGE__->register_method(
821 method => "update_hold",
822 api_name => "open-ils.circ.hold.update",
824 desc => "Updates the specified hold. $update_hold_desc",
826 {desc => 'Authentication token', type => 'string'},
827 {desc => 'Hold Object', type => 'object'},
828 {desc => 'Hash of values to be applied', type => 'object'}
831 desc => 'Hold ID on success, event on error',
837 __PACKAGE__->register_method(
838 method => "batch_update_hold",
839 api_name => "open-ils.circ.hold.update.batch",
842 desc => "Updates the specified hold(s). $update_hold_desc",
844 {desc => 'Authentication token', type => 'string'},
845 {desc => 'Array of hold obejcts', type => 'array' },
846 {desc => 'Array of hashes of values to be applied', type => 'array' }
849 desc => 'Hold ID per success, event per error',
855 my($self, $client, $auth, $hold, $values) = @_;
856 my $e = new_editor(authtoken=>$auth, xact=>1);
857 return $e->die_event unless $e->checkauth;
858 my $resp = update_hold_impl($self, $e, $hold, $values);
859 if ($U->event_code($resp)) {
863 $e->commit; # FIXME: update_hold_impl already does $e->commit ??
867 sub batch_update_hold {
868 my($self, $client, $auth, $hold_list, $values_list) = @_;
869 my $e = new_editor(authtoken=>$auth);
870 return $e->die_event unless $e->checkauth;
872 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.
874 $values_list ||= []; # FIXME: either move this above $count declaration, or send an event if both lists undef. Probably the latter.
876 # FIXME: Failing over to [] guarantees warnings for "Use of unitialized value" in update_hold_impl call.
877 # FIXME: We should be sure we only call update_hold_impl with hold object OR hash, not both.
879 for my $idx (0..$count-1) {
881 my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
882 $e->xact_commit unless $U->event_code($resp);
883 $client->respond($resp);
887 return undef; # not in the register return type, assuming we should always have at least one list populated
890 sub update_hold_impl {
891 my($self, $e, $hold, $values) = @_;
893 my $need_retarget = 0;
896 $hold = $e->retrieve_action_hold_request($values->{id})
897 or return $e->die_event;
898 for my $k (keys %$values) {
899 # Outside of pickup_lib (covered by the first regex) I don't know when these would currently change.
900 # But hey, why not cover things that may happen later?
901 if ($k =~ '_(lib|ou)$' || $k eq 'target' || $k eq 'hold_type' || $k eq 'requestor' || $k eq 'selection_depth' || $k eq 'holdable_formats') {
902 if (defined $values->{$k} && defined $hold->$k() && $values->{$k} ne $hold->$k()) {
903 # Value changed? RETARGET!
905 } elsif (defined $hold->$k() != defined $values->{$k}) {
906 # Value being set or cleared? RETARGET!
910 if (defined $values->{$k}) {
911 $hold->$k($values->{$k});
913 my $f = "clear_$k"; $hold->$f();
918 my $orig_hold = $e->retrieve_action_hold_request($hold->id)
919 or return $e->die_event;
921 # don't allow the user to be changed
922 return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
924 if($hold->usr ne $e->requestor->id) {
925 # if the hold is for a different user, make sure the
926 # requestor has the appropriate permissions
927 my $usr = $e->retrieve_actor_user($hold->usr)
928 or return $e->die_event;
929 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
933 # --------------------------------------------------------------
934 # Changing the request time is like playing God
935 # --------------------------------------------------------------
936 if($hold->request_time ne $orig_hold->request_time) {
937 return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
938 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
942 # --------------------------------------------------------------
943 # Code for making sure staff have appropriate permissons for cut_in_line
944 # This, as is, doesn't prevent a user from cutting their own holds in line
946 # --------------------------------------------------------------
947 if($U->is_true($hold->cut_in_line) ne $U->is_true($orig_hold->cut_in_line)) {
948 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
952 # --------------------------------------------------------------
953 # Disallow hold suspencion if the hold is already captured.
954 # --------------------------------------------------------------
955 if ($U->is_true($hold->frozen) and not $U->is_true($orig_hold->frozen)) {
956 $hold_status = _hold_status($e, $hold);
957 if ($hold_status > 2 && $hold_status != 7) { # hold is captured
958 $logger->info("bypassing hold freeze on captured hold");
959 return OpenILS::Event->new('HOLD_SUSPEND_AFTER_CAPTURE');
964 # --------------------------------------------------------------
965 # if the hold is on the holds shelf or in transit and the pickup
966 # lib changes we need to create a new transit.
967 # --------------------------------------------------------------
968 if($orig_hold->pickup_lib ne $hold->pickup_lib) {
970 $hold_status = _hold_status($e, $hold) unless $hold_status;
972 if($hold_status == 3) { # in transit
974 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
975 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
977 $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
979 # update the transit to reflect the new pickup location
980 my $transit = $e->search_action_hold_transit_copy(
981 {hold=>$hold->id, dest_recv_time => undef})->[0]
982 or return $e->die_event;
984 $transit->prev_dest($transit->dest); # mark the previous destination on the transit
985 $transit->dest($hold->pickup_lib);
986 $e->update_action_hold_transit_copy($transit) or return $e->die_event;
988 } elsif($hold_status == 4 or $hold_status == 5 or $hold_status == 8) { # on holds shelf
990 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
991 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
993 $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
995 if ($hold->pickup_lib eq $orig_hold->current_shelf_lib) {
996 # This can happen if the pickup lib is changed while the hold is
997 # on the shelf, then changed back to the original pickup lib.
998 # Restore the original shelf_expire_time to prevent abuse.
999 set_hold_shelf_expire_time(undef, $hold, $e, $hold->shelf_time);
1002 # clear to prevent premature shelf expiration
1003 $hold->clear_shelf_expire_time;
1008 if($U->is_true($hold->frozen)) {
1009 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
1010 $hold->clear_current_copy;
1011 $hold->clear_prev_check_time;
1012 # Clear expire_time to prevent frozen holds from expiring.
1013 $logger->info("clearing expire_time for frozen hold ".$hold->id);
1014 $hold->clear_expire_time;
1017 # If the hold_expire_time is in the past && is not equal to the
1018 # original expire_time, then reset the expire time to be in the
1020 if ($hold->expire_time && $U->datecmp($hold->expire_time) == -1 && $U->datecmp($hold->expire_time, $orig_hold->expire_time) != 0) {
1021 $hold->expire_time(calculate_expire_time($hold->request_lib));
1024 # If the hold is reactivated, reset the expire_time.
1025 if(!$U->is_true($hold->frozen) && $U->is_true($orig_hold->frozen)) {
1026 $logger->info("Reset expire_time on activated hold ".$hold->id);
1027 $hold->expire_time(calculate_expire_time($hold->request_lib));
1030 $e->update_action_hold_request($hold) or return $e->die_event;
1033 if(!$U->is_true($hold->frozen) && $U->is_true($orig_hold->frozen)) {
1034 $logger->info("Running targeter on activated hold ".$hold->id);
1035 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1038 # a change to mint-condition changes the set of potential copies, so retarget the hold;
1039 if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
1040 _reset_hold($self, $e->requestor, $hold)
1041 } elsif($need_retarget && !defined $hold->capture_time()) { # If needed, retarget the hold due to changes
1043 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1049 # this does not update the hold in the DB. It only
1050 # sets the shelf_expire_time field on the hold object.
1051 # start_time is optional and defaults to 'now'
1052 sub set_hold_shelf_expire_time {
1053 my ($class, $hold, $editor, $start_time) = @_;
1055 my $shelf_expire = $U->ou_ancestor_setting_value(
1057 'circ.holds.default_shelf_expire_interval',
1061 return undef unless $shelf_expire;
1063 $start_time = ($start_time) ?
1064 DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time)) :
1067 my $seconds = OpenSRF::Utils->interval_to_seconds($shelf_expire);
1068 my $expire_time = $start_time->add(seconds => $seconds);
1070 # if the shelf expire time overlaps with a pickup lib's
1071 # closed date, push it out to the first open date
1072 my $dateinfo = $U->storagereq(
1073 'open-ils.storage.actor.org_unit.closed_date.overlap',
1074 $hold->pickup_lib, $expire_time->strftime('%FT%T%z'));
1077 my $dt_parser = DateTime::Format::ISO8601->new;
1078 $expire_time = $dt_parser->parse_datetime(cleanse_ISO8601($dateinfo->{end}));
1080 # TODO: enable/disable time bump via setting?
1081 $expire_time->set(hour => '23', minute => '59', second => '59');
1083 $logger->info("circulator: shelf_expire_time overlaps".
1084 " with closed date, pushing expire time to $expire_time");
1087 $hold->shelf_expire_time($expire_time->strftime('%FT%T%z'));
1093 my($e, $orig_hold, $hold, $copy) = @_;
1094 my $src = $orig_hold->pickup_lib;
1095 my $dest = $hold->pickup_lib;
1097 $logger->info("putting hold into transit on pickup_lib update");
1099 my $transit = Fieldmapper::action::hold_transit_copy->new;
1100 $transit->hold($hold->id);
1101 $transit->source($src);
1102 $transit->dest($dest);
1103 $transit->target_copy($copy->id);
1104 $transit->source_send_time('now');
1105 $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
1107 $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
1108 $copy->editor($e->requestor->id);
1109 $copy->edit_date('now');
1111 $e->create_action_hold_transit_copy($transit) or return $e->die_event;
1112 $e->update_asset_copy($copy) or return $e->die_event;
1116 # if the hold is frozen, this method ensures that the hold is not "targeted",
1117 # that is, it clears the current_copy and prev_check_time to essentiallly
1118 # reset the hold. If it is being activated, it runs the targeter in the background
1119 sub update_hold_if_frozen {
1120 my($self, $e, $hold, $orig_hold) = @_;
1121 return if $hold->capture_time;
1123 if($U->is_true($hold->frozen)) {
1124 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
1125 $hold->clear_current_copy;
1126 $hold->clear_prev_check_time;
1129 if($U->is_true($orig_hold->frozen)) {
1130 $logger->info("Running targeter on activated hold ".$hold->id);
1131 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1136 __PACKAGE__->register_method(
1137 method => "hold_note_CUD",
1138 api_name => "open-ils.circ.hold_request.note.cud",
1140 desc => 'Create, update or delete a hold request note. If the operator (from Auth. token) '
1141 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
1143 { desc => 'Authentication token', type => 'string' },
1144 { desc => 'Hold note object', type => 'object' }
1147 desc => 'Returns the note ID, event on error'
1153 my($self, $conn, $auth, $note) = @_;
1155 my $e = new_editor(authtoken => $auth, xact => 1);
1156 return $e->die_event unless $e->checkauth;
1158 my $hold = $e->retrieve_action_hold_request($note->hold)
1159 or return $e->die_event;
1161 if($hold->usr ne $e->requestor->id) {
1162 my $usr = $e->retrieve_actor_user($hold->usr);
1163 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
1164 $note->staff('t') if $note->isnew;
1168 $e->create_action_hold_request_note($note) or return $e->die_event;
1169 } elsif($note->ischanged) {
1170 $e->update_action_hold_request_note($note) or return $e->die_event;
1171 } elsif($note->isdeleted) {
1172 $e->delete_action_hold_request_note($note) or return $e->die_event;
1180 __PACKAGE__->register_method(
1181 method => "retrieve_hold_status",
1182 api_name => "open-ils.circ.hold.status.retrieve",
1184 desc => 'Calculates the current status of the hold. The requestor must have ' .
1185 'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
1187 { desc => 'Hold ID', type => 'number' }
1190 # type => 'number', # event sometimes
1191 desc => <<'END_OF_DESC'
1192 Returns event on error or:
1193 -1 on error (for now),
1194 1 for 'waiting for copy to become available',
1195 2 for 'waiting for copy capture',
1198 5 for 'hold-shelf-delay'
1201 8 for 'captured, on wrong hold shelf'
1207 sub retrieve_hold_status {
1208 my($self, $client, $auth, $hold_id) = @_;
1210 my $e = new_editor(authtoken => $auth);
1211 return $e->event unless $e->checkauth;
1212 my $hold = $e->retrieve_action_hold_request($hold_id)
1213 or return $e->event;
1215 if( $e->requestor->id != $hold->usr ) {
1216 return $e->event unless $e->allowed('VIEW_HOLD');
1219 return _hold_status($e, $hold);
1225 if ($hold->cancel_time) {
1228 if ($U->is_true($hold->frozen) && !$hold->capture_time) {
1231 if ($hold->current_shelf_lib and $hold->current_shelf_lib ne $hold->pickup_lib) {
1234 return 1 unless $hold->current_copy;
1235 return 2 unless $hold->capture_time;
1237 my $copy = $hold->current_copy;
1238 unless( ref $copy ) {
1239 $copy = $e->retrieve_asset_copy($hold->current_copy)
1240 or return $e->event;
1243 return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
1245 if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
1247 my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
1248 return 4 unless $hs_wait_interval;
1250 # if a hold_shelf_status_delay interval is defined and start_time plus
1251 # the interval is greater than now, consider the hold to be in the virtual
1252 # "on its way to the holds shelf" status. Return 5.
1254 my $transit = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
1255 my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
1256 $start_time = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
1257 my $end_time = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
1259 return 5 if $end_time > DateTime->now;
1268 __PACKAGE__->register_method(
1269 method => "retrieve_hold_queue_stats",
1270 api_name => "open-ils.circ.hold.queue_stats.retrieve",
1272 desc => 'Returns summary data about the state of a hold',
1274 { desc => 'Authentication token', type => 'string'},
1275 { desc => 'Hold ID', type => 'number'},
1278 desc => q/Summary object with keys:
1279 total_holds : total holds in queue
1280 queue_position : current queue position
1281 potential_copies : number of potential copies for this hold
1282 estimated_wait : estimated wait time in days
1283 status : hold status
1284 -1 => error or unexpected state,
1285 1 => 'waiting for copy to become available',
1286 2 => 'waiting for copy capture',
1289 5 => 'hold-shelf-delay'
1296 sub retrieve_hold_queue_stats {
1297 my($self, $conn, $auth, $hold_id) = @_;
1298 my $e = new_editor(authtoken => $auth);
1299 return $e->event unless $e->checkauth;
1300 my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1301 if($e->requestor->id != $hold->usr) {
1302 return $e->event unless $e->allowed('VIEW_HOLD');
1304 return retrieve_hold_queue_status_impl($e, $hold);
1307 sub retrieve_hold_queue_status_impl {
1311 # The holds queue is defined as the distinct set of holds that share at
1312 # least one potential copy with the context hold, plus any holds that
1313 # share the same hold type and target. The latter part exists to
1314 # accomodate holds that currently have no potential copies
1315 my $q_holds = $e->json_query({
1317 # fetch cut_in_line and request_time since they're in the order_by
1318 # and we're asking for distinct values
1319 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1326 'field' => 'target_copy',
1327 'fkey' => 'target_copy'
1336 "field" => "cut_in_line",
1337 "transform" => "coalesce",
1339 "direction" => "desc"
1341 { "class" => "ahr", "field" => "request_time" }
1345 '+ahcm2' => { hold => $hold->id }
1349 if (!@$q_holds) { # none? maybe we don't have a map ...
1350 $q_holds = $e->json_query({
1351 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1356 "field" => "cut_in_line",
1357 "transform" => "coalesce",
1359 "direction" => "desc"
1361 { "class" => "ahr", "field" => "request_time" }
1364 hold_type => $hold->hold_type,
1365 target => $hold->target
1372 for my $h (@$q_holds) {
1373 last if $h->{id} == $hold->id;
1377 my $hold_data = $e->json_query({
1379 acp => [ {column => 'id', transform => 'count', aggregate => 1, alias => 'count'} ],
1380 ccm => [ {column =>'avg_wait_time'} ]
1386 ccm => {type => 'left'}
1391 where => {'+ahcm' => {hold => $hold->id} }
1394 my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1396 my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1397 my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1398 $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1399 $default_wait ||= '0 seconds';
1401 # Estimated wait time is the average wait time across the set
1402 # of potential copies, divided by the number of potential copies
1403 # times the queue position.
1405 my $combined_secs = 0;
1406 my $num_potentials = 0;
1408 for my $wait_data (@$hold_data) {
1409 my $count += $wait_data->{count};
1410 $combined_secs += $count *
1411 OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1412 $num_potentials += $count;
1415 my $estimated_wait = -1;
1417 if($num_potentials) {
1418 my $avg_wait = $combined_secs / $num_potentials;
1419 $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1420 $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1424 total_holds => scalar(@$q_holds),
1425 queue_position => $qpos,
1426 potential_copies => $num_potentials,
1427 status => _hold_status( $e, $hold ),
1428 estimated_wait => int($estimated_wait)
1433 sub fetch_open_hold_by_current_copy {
1436 my $hold = $apputils->simplereq(
1438 'open-ils.cstore.direct.action.hold_request.search.atomic',
1439 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1440 return $hold->[0] if ref($hold);
1444 sub fetch_related_holds {
1447 return $apputils->simplereq(
1449 'open-ils.cstore.direct.action.hold_request.search.atomic',
1450 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1454 __PACKAGE__->register_method(
1455 method => "hold_pull_list",
1456 api_name => "open-ils.circ.hold_pull_list.retrieve",
1458 desc => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1459 'The location is determined by the login session.',
1461 { desc => 'Limit (optional)', type => 'number'},
1462 { desc => 'Offset (optional)', type => 'number'},
1465 desc => 'reference to a list of holds, or event on failure',
1470 __PACKAGE__->register_method(
1471 method => "hold_pull_list",
1472 api_name => "open-ils.circ.hold_pull_list.id_list.retrieve",
1474 desc => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1475 'The location is determined by the login session.',
1477 { desc => 'Limit (optional)', type => 'number'},
1478 { desc => 'Offset (optional)', type => 'number'},
1481 desc => 'reference to a list of holds, or event on failure',
1486 __PACKAGE__->register_method(
1487 method => "hold_pull_list",
1488 api_name => "open-ils.circ.hold_pull_list.retrieve.count",
1490 desc => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1491 'The location is determined by the login session.',
1493 { desc => 'Limit (optional)', type => 'number'},
1494 { desc => 'Offset (optional)', type => 'number'},
1497 desc => 'Holds count (integer), or event on failure',
1504 sub hold_pull_list {
1505 my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1506 my( $reqr, $evt ) = $U->checkses($authtoken);
1507 return $evt if $evt;
1509 my $org = $reqr->ws_ou || $reqr->home_ou;
1510 # the perm locaiton shouldn't really matter here since holds
1511 # will exist all over and VIEW_HOLDS should be universal
1512 $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1513 return $evt if $evt;
1515 if($self->api_name =~ /count/) {
1517 my $count = $U->storagereq(
1518 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1519 $org, $limit, $offset );
1521 $logger->info("Grabbing pull list for org unit $org with $count items");
1524 } elsif( $self->api_name =~ /id_list/ ) {
1525 return $U->storagereq(
1526 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1527 $org, $limit, $offset );
1530 return $U->storagereq(
1531 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1532 $org, $limit, $offset );
1536 __PACKAGE__->register_method(
1537 method => "print_hold_pull_list",
1538 api_name => "open-ils.circ.hold_pull_list.print",
1540 desc => 'Returns an HTML-formatted holds pull list',
1542 { desc => 'Authtoken', type => 'string'},
1543 { desc => 'Org unit ID. Optional, defaults to workstation org unit', type => 'number'},
1546 desc => 'HTML string',
1552 sub print_hold_pull_list {
1553 my($self, $client, $auth, $org_id) = @_;
1555 my $e = new_editor(authtoken=>$auth);
1556 return $e->event unless $e->checkauth;
1558 $org_id = (defined $org_id) ? $org_id : $e->requestor->ws_ou;
1559 return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1561 my $hold_ids = $U->storagereq(
1562 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1565 return undef unless @$hold_ids;
1567 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1569 # Holds will /NOT/ be in order after this ...
1570 my $holds = $e->search_action_hold_request({id => $hold_ids}, {substream => 1});
1571 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1573 # ... so we must resort.
1574 my $hold_map = +{map { $_->id => $_ } @$holds};
1575 my $sorted_holds = [];
1576 push @$sorted_holds, $hold_map->{$_} foreach @$hold_ids;
1578 return $U->fire_object_event(
1579 undef, "ahr.format.pull_list", $sorted_holds,
1580 $org_id, undef, undef, $client
1585 __PACKAGE__->register_method(
1586 method => "print_hold_pull_list_stream",
1588 api_name => "open-ils.circ.hold_pull_list.print.stream",
1590 desc => 'Returns a stream of fleshed holds',
1592 { desc => 'Authtoken', type => 'string'},
1593 { 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)',
1598 desc => 'A stream of fleshed holds',
1604 sub print_hold_pull_list_stream {
1605 my($self, $client, $auth, $params) = @_;
1607 my $e = new_editor(authtoken=>$auth);
1608 return $e->die_event unless $e->checkauth;
1610 delete($$params{org_id}) unless (int($$params{org_id}));
1611 delete($$params{limit}) unless (int($$params{limit}));
1612 delete($$params{offset}) unless (int($$params{offset}));
1613 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1614 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1615 $$params{chunk_size} ||= 10;
1617 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1618 return $e->die_event unless $e->allowed('VIEW_HOLD', $$params{org_id });
1621 if ($$params{sort} && @{ $$params{sort} }) {
1622 for my $s (@{ $$params{sort} }) {
1623 if ($s eq 'acplo.position') {
1625 "class" => "acplo", "field" => "position",
1626 "transform" => "coalesce", "params" => [999]
1628 } elsif ($s eq 'prefix') {
1629 push @$sort, {"class" => "acnp", "field" => "label_sortkey"};
1630 } elsif ($s eq 'call_number') {
1631 push @$sort, {"class" => "acn", "field" => "label_sortkey"};
1632 } elsif ($s eq 'suffix') {
1633 push @$sort, {"class" => "acns", "field" => "label_sortkey"};
1634 } elsif ($s eq 'request_time') {
1635 push @$sort, {"class" => "ahr", "field" => "request_time"};
1639 push @$sort, {"class" => "ahr", "field" => "request_time"};
1642 my $holds_ids = $e->json_query(
1644 "select" => {"ahr" => ["id"]},
1649 "fkey" => "current_copy",
1651 "circ_lib" => $$params{org_id}, "status" => [0,7]
1656 "fkey" => "call_number",
1670 "fkey" => "circ_lib",
1673 "location" => {"=" => {"+acp" => "location"}}
1682 "capture_time" => undef,
1683 "cancel_time" => undef,
1685 {"expire_time" => undef },
1686 {"expire_time" => {">" => "now"}}
1690 (@$sort ? (order_by => $sort) : ()),
1691 ($$params{limit} ? (limit => $$params{limit}) : ()),
1692 ($$params{offset} ? (offset => $$params{offset}) : ())
1693 }, {"substream" => 1}
1694 ) or return $e->die_event;
1696 $logger->info("about to stream back " . scalar(@$holds_ids) . " holds");
1699 for my $hid (@$holds_ids) {
1700 push @chunk, $e->retrieve_action_hold_request([
1704 "ahr" => ["usr", "current_copy"],
1706 "acp" => ["location", "call_number", "parts"],
1707 "acn" => ["record","prefix","suffix"]
1712 if (@chunk >= $$params{chunk_size}) {
1713 $client->respond( \@chunk );
1717 $client->respond_complete( \@chunk ) if (@chunk);
1724 __PACKAGE__->register_method(
1725 method => 'fetch_hold_notify',
1726 api_name => 'open-ils.circ.hold_notification.retrieve_by_hold',
1729 Returns a list of hold notification objects based on hold id.
1730 @param authtoken The loggin session key
1731 @param holdid The id of the hold whose notifications we want to retrieve
1732 @return An array of hold notification objects, event on error.
1736 sub fetch_hold_notify {
1737 my( $self, $conn, $authtoken, $holdid ) = @_;
1738 my( $requestor, $evt ) = $U->checkses($authtoken);
1739 return $evt if $evt;
1740 my ($hold, $patron);
1741 ($hold, $evt) = $U->fetch_hold($holdid);
1742 return $evt if $evt;
1743 ($patron, $evt) = $U->fetch_user($hold->usr);
1744 return $evt if $evt;
1746 $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1747 return $evt if $evt;
1749 $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1750 return $U->cstorereq(
1751 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1755 __PACKAGE__->register_method(
1756 method => 'create_hold_notify',
1757 api_name => 'open-ils.circ.hold_notification.create',
1759 Creates a new hold notification object
1760 @param authtoken The login session key
1761 @param notification The hold notification object to create
1762 @return ID of the new object on success, Event on error
1766 sub create_hold_notify {
1767 my( $self, $conn, $auth, $note ) = @_;
1768 my $e = new_editor(authtoken=>$auth, xact=>1);
1769 return $e->die_event unless $e->checkauth;
1771 my $hold = $e->retrieve_action_hold_request($note->hold)
1772 or return $e->die_event;
1773 my $patron = $e->retrieve_actor_user($hold->usr)
1774 or return $e->die_event;
1776 return $e->die_event unless
1777 $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1779 $note->notify_staff($e->requestor->id);
1780 $e->create_action_hold_notification($note) or return $e->die_event;
1785 __PACKAGE__->register_method(
1786 method => 'create_hold_note',
1787 api_name => 'open-ils.circ.hold_note.create',
1789 Creates a new hold request note object
1790 @param authtoken The login session key
1791 @param note The hold note object to create
1792 @return ID of the new object on success, Event on error
1796 sub create_hold_note {
1797 my( $self, $conn, $auth, $note ) = @_;
1798 my $e = new_editor(authtoken=>$auth, xact=>1);
1799 return $e->die_event unless $e->checkauth;
1801 my $hold = $e->retrieve_action_hold_request($note->hold)
1802 or return $e->die_event;
1803 my $patron = $e->retrieve_actor_user($hold->usr)
1804 or return $e->die_event;
1806 return $e->die_event unless
1807 $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn. Probably want something more specific
1809 $e->create_action_hold_request_note($note) or return $e->die_event;
1814 __PACKAGE__->register_method(
1815 method => 'reset_hold',
1816 api_name => 'open-ils.circ.hold.reset',
1818 Un-captures and un-targets a hold, essentially returning
1819 it to the state it was in directly after it was placed,
1820 then attempts to re-target the hold
1821 @param authtoken The login session key
1822 @param holdid The id of the hold
1828 my( $self, $conn, $auth, $holdid ) = @_;
1830 my ($hold, $evt) = $U->fetch_hold($holdid);
1831 return $evt if $evt;
1832 ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1833 return $evt if $evt;
1834 $evt = _reset_hold($self, $reqr, $hold);
1835 return $evt if $evt;
1840 __PACKAGE__->register_method(
1841 method => 'reset_hold_batch',
1842 api_name => 'open-ils.circ.hold.reset.batch'
1845 sub reset_hold_batch {
1846 my($self, $conn, $auth, $hold_ids) = @_;
1848 my $e = new_editor(authtoken => $auth);
1849 return $e->event unless $e->checkauth;
1851 for my $hold_id ($hold_ids) {
1853 my $hold = $e->retrieve_action_hold_request(
1854 [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}])
1855 or return $e->event;
1857 next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1858 _reset_hold($self, $e->requestor, $hold);
1866 my ($self, $reqr, $hold) = @_;
1868 my $e = new_editor(xact =>1, requestor => $reqr);
1870 $logger->info("reseting hold ".$hold->id);
1872 my $hid = $hold->id;
1874 if( $hold->capture_time and $hold->current_copy ) {
1876 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1877 or return $e->die_event;
1879 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1880 $logger->info("setting copy to status 'reshelving' on hold retarget");
1881 $copy->status(OILS_COPY_STATUS_RESHELVING);
1882 $copy->editor($e->requestor->id);
1883 $copy->edit_date('now');
1884 $e->update_asset_copy($copy) or return $e->die_event;
1886 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1888 # We don't want the copy to remain "in transit"
1889 $copy->status(OILS_COPY_STATUS_RESHELVING);
1890 $logger->warn("! reseting hold [$hid] that is in transit");
1891 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1894 my $trans = $e->retrieve_action_transit_copy($transid);
1896 $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1897 my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1, 1);
1898 $logger->info("Transit abort completed with result $evt");
1899 unless ("$evt" eq 1) {
1908 $hold->clear_capture_time;
1909 $hold->clear_current_copy;
1910 $hold->clear_shelf_time;
1911 $hold->clear_shelf_expire_time;
1912 $hold->clear_current_shelf_lib;
1914 $e->update_action_hold_request($hold) or return $e->die_event;
1918 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1924 __PACKAGE__->register_method(
1925 method => 'fetch_open_title_holds',
1926 api_name => 'open-ils.circ.open_holds.retrieve',
1928 Returns a list ids of un-fulfilled holds for a given title id
1929 @param authtoken The login session key
1930 @param id the id of the item whose holds we want to retrieve
1931 @param type The hold type - M, T, I, V, C, F, R
1935 sub fetch_open_title_holds {
1936 my( $self, $conn, $auth, $id, $type, $org ) = @_;
1937 my $e = new_editor( authtoken => $auth );
1938 return $e->event unless $e->checkauth;
1941 $org ||= $e->requestor->ws_ou;
1943 # return $e->search_action_hold_request(
1944 # { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1946 # XXX make me return IDs in the future ^--
1947 my $holds = $e->search_action_hold_request(
1950 cancel_time => undef,
1952 fulfillment_time => undef
1956 flesh_hold_transits($holds);
1961 sub flesh_hold_transits {
1963 for my $hold ( @$holds ) {
1965 $apputils->simplereq(
1967 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1968 { hold => $hold->id },
1969 { order_by => { ahtc => 'id desc' }, limit => 1 }
1975 sub flesh_hold_notices {
1976 my( $holds, $e ) = @_;
1977 $e ||= new_editor();
1979 for my $hold (@$holds) {
1980 my $notices = $e->search_action_hold_notification(
1982 { hold => $hold->id },
1983 { order_by => { anh => 'notify_time desc' } },
1988 $hold->notify_count(scalar(@$notices));
1990 my $n = $e->retrieve_action_hold_notification($$notices[0])
1991 or return $e->event;
1992 $hold->notify_time($n->notify_time);
1998 __PACKAGE__->register_method(
1999 method => 'fetch_captured_holds',
2000 api_name => 'open-ils.circ.captured_holds.on_shelf.retrieve',
2004 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
2005 @param authtoken The login session key
2006 @param org The org id of the location in question
2007 @param match_copy A specific copy to limit to
2011 __PACKAGE__->register_method(
2012 method => 'fetch_captured_holds',
2013 api_name => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
2017 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
2018 @param authtoken The login session key
2019 @param org The org id of the location in question
2020 @param match_copy A specific copy to limit to
2024 __PACKAGE__->register_method(
2025 method => 'fetch_captured_holds',
2026 api_name => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
2030 Returns list ids of shelf-expired un-fulfilled holds for a given title id
2031 @param authtoken The login session key
2032 @param org The org id of the location in question
2033 @param match_copy A specific copy to limit to
2038 sub fetch_captured_holds {
2039 my( $self, $conn, $auth, $org, $match_copy ) = @_;
2041 my $e = new_editor(authtoken => $auth);
2042 return $e->die_event unless $e->checkauth;
2043 return $e->die_event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
2045 $org ||= $e->requestor->ws_ou;
2047 my $current_copy = { '!=' => undef };
2048 $current_copy = { '=' => $match_copy } if $match_copy;
2051 select => { alhr => ['id'] },
2056 fkey => 'current_copy'
2061 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
2063 capture_time => { "!=" => undef },
2064 current_copy => $current_copy,
2065 fulfillment_time => undef,
2066 current_shelf_lib => $org
2070 if($self->api_name =~ /expired/) {
2071 $query->{'where'}->{'+alhr'}->{'-or'} = {
2072 shelf_expire_time => { '<' => 'now'},
2073 cancel_time => { '!=' => undef },
2076 my $hold_ids = $e->json_query( $query );
2078 for my $hold_id (@$hold_ids) {
2079 if($self->api_name =~ /id_list/) {
2080 $conn->respond($hold_id->{id});
2084 $e->retrieve_action_hold_request([
2088 flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
2089 order_by => {anh => 'notify_time desc'}
2099 __PACKAGE__->register_method(
2100 method => "print_expired_holds_stream",
2101 api_name => "open-ils.circ.captured_holds.expired.print.stream",
2105 sub print_expired_holds_stream {
2106 my ($self, $client, $auth, $params) = @_;
2108 # No need to check specific permissions: we're going to call another method
2109 # that will do that.
2110 my $e = new_editor("authtoken" => $auth);
2111 return $e->die_event unless $e->checkauth;
2113 delete($$params{org_id}) unless (int($$params{org_id}));
2114 delete($$params{limit}) unless (int($$params{limit}));
2115 delete($$params{offset}) unless (int($$params{offset}));
2116 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
2117 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
2118 $$params{chunk_size} ||= 10;
2120 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
2122 my @hold_ids = $self->method_lookup(
2123 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
2124 )->run($auth, $params->{"org_id"});
2129 } elsif (defined $U->event_code($hold_ids[0])) {
2131 return $hold_ids[0];
2134 $logger->info("about to stream back up to " . scalar(@hold_ids) . " expired holds");
2137 my @hid_chunk = splice @hold_ids, 0, $params->{"chunk_size"};
2139 my $result_chunk = $e->json_query({
2141 "acp" => ["barcode"],
2143 first_given_name second_given_name family_name alias
2152 "field" => "id", "fkey" => "current_copy",
2155 "field" => "id", "fkey" => "call_number",
2158 "field" => "id", "fkey" => "record"
2162 "acpl" => {"field" => "id", "fkey" => "location"}
2165 "au" => {"field" => "id", "fkey" => "usr"}
2168 "where" => {"+ahr" => {"id" => \@hid_chunk}}
2169 }) or return $e->die_event;
2170 $client->respond($result_chunk);
2177 __PACKAGE__->register_method(
2178 method => "check_title_hold_batch",
2179 api_name => "open-ils.circ.title_hold.is_possible.batch",
2182 desc => '@see open-ils.circ.title_hold.is_possible.batch',
2184 { desc => 'Authentication token', type => 'string'},
2185 { desc => 'Array of Hash of named parameters', type => 'array'},
2188 desc => 'Array of response objects',
2194 sub check_title_hold_batch {
2195 my($self, $client, $authtoken, $param_list, $oargs) = @_;
2196 foreach (@$param_list) {
2197 my ($res) = $self->method_lookup('open-ils.circ.title_hold.is_possible')->run($authtoken, $_, $oargs);
2198 $client->respond($res);
2204 __PACKAGE__->register_method(
2205 method => "check_title_hold",
2206 api_name => "open-ils.circ.title_hold.is_possible",
2208 desc => 'Determines if a hold were to be placed by a given user, ' .
2209 'whether or not said hold would have any potential copies to fulfill it.' .
2210 'The named paramaters of the second argument include: ' .
2211 'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
2212 'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' ,
2214 { desc => 'Authentication token', type => 'string'},
2215 { desc => 'Hash of named parameters', type => 'object'},
2218 desc => 'List of new message IDs (empty if none)',
2224 =head3 check_title_hold (token, hash)
2226 The named fields in the hash are:
2228 patronid - ID of the hold recipient (required)
2229 depth - hold range depth (default 0)
2230 pickup_lib - destination for hold, fallback value for selection_ou
2231 selection_ou - ID of org_unit establishing hard and soft hold boundary settings
2232 issuanceid - ID of the issuance to be held, required for Issuance level hold
2233 partid - ID of the monograph part to be held, required for monograph part level hold
2234 titleid - ID (BRN) of the title to be held, required for Title level hold
2235 volume_id - required for Volume level hold
2236 copy_id - required for Copy level hold
2237 mrid - required for Meta-record level hold
2238 hold_type - T, C (or R or F), I, V or M for Title, Copy, Issuance, Volume or Meta-record (default "T")
2240 All key/value pairs are passed on to do_possibility_checks.
2244 # FIXME: better params checking. what other params are required, if any?
2245 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
2246 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still
2247 # used in conditionals, where it may be undefined, causing a warning.
2248 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
2250 sub check_title_hold {
2251 my( $self, $client, $authtoken, $params ) = @_;
2252 my $e = new_editor(authtoken=>$authtoken);
2253 return $e->event unless $e->checkauth;
2255 my %params = %$params;
2256 my $depth = $params{depth} || 0;
2257 my $selection_ou = $params{selection_ou} || $params{pickup_lib};
2258 my $oargs = $params{oargs} || {};
2260 if($oargs->{events}) {
2261 @{$oargs->{events}} = grep { $e->allowed($_ . '.override', $e->requestor->ws_ou); } @{$oargs->{events}};
2265 my $patron = $e->retrieve_actor_user($params{patronid})
2266 or return $e->event;
2268 if( $e->requestor->id ne $patron->id ) {
2269 return $e->event unless
2270 $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
2273 return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
2275 my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
2276 or return $e->event;
2278 my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
2279 my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
2282 my $return_depth = $hard_boundary; # default depth to return on success
2283 if(defined $soft_boundary and $depth < $soft_boundary) {
2284 # work up the tree and as soon as we find a potential copy, use that depth
2285 # also, make sure we don't go past the hard boundary if it exists
2287 # our min boundary is the greater of user-specified boundary or hard boundary
2288 my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?
2289 $hard_boundary : $depth;
2291 my $depth = $soft_boundary;
2292 while($depth >= $min_depth) {
2293 $logger->info("performing hold possibility check with soft boundary $depth");
2294 @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
2296 $return_depth = $depth;
2301 } elsif(defined $hard_boundary and $depth < $hard_boundary) {
2302 # there is no soft boundary, enforce the hard boundary if it exists
2303 $logger->info("performing hold possibility check with hard boundary $hard_boundary");
2304 @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
2306 # no boundaries defined, fall back to user specifed boundary or no boundary
2307 $logger->info("performing hold possibility check with no boundary");
2308 @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
2311 my $place_unfillable = 0;
2312 $place_unfillable = 1 if $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
2317 "depth" => $return_depth,
2318 "local_avail" => $status[1]
2320 } elsif ($status[2]) {
2321 my $n = scalar @{$status[2]};
2322 return {"success" => 0, "last_event" => $status[2]->[$n - 1], "age_protected_copy" => $status[3], "place_unfillable" => $place_unfillable};
2324 return {"success" => 0, "age_protected_copy" => $status[3], "place_unfillable" => $place_unfillable};
2330 sub do_possibility_checks {
2331 my($e, $patron, $request_lib, $depth, %params) = @_;
2333 my $issuanceid = $params{issuanceid} || "";
2334 my $partid = $params{partid} || "";
2335 my $titleid = $params{titleid} || "";
2336 my $volid = $params{volume_id};
2337 my $copyid = $params{copy_id};
2338 my $mrid = $params{mrid} || "";
2339 my $pickup_lib = $params{pickup_lib};
2340 my $hold_type = $params{hold_type} || 'T';
2341 my $selection_ou = $params{selection_ou} || $pickup_lib;
2342 my $holdable_formats = $params{holdable_formats};
2343 my $oargs = $params{oargs} || {};
2350 if( $hold_type eq OILS_HOLD_TYPE_FORCE || $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_COPY ) {
2352 return $e->event unless $copy = $e->retrieve_asset_copy($copyid);
2353 return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
2354 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2356 return (1, 1, []) if( $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_FORCE);
2357 return verify_copy_for_hold(
2358 $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib, $oargs
2361 } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2363 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
2364 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2366 return _check_volume_hold_is_possible(
2367 $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2370 } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
2372 return _check_title_hold_is_possible(
2373 $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, undef, $oargs
2376 } elsif( $hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2378 return _check_issuance_hold_is_possible(
2379 $issuanceid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2382 } elsif( $hold_type eq OILS_HOLD_TYPE_MONOPART ) {
2384 return _check_monopart_hold_is_possible(
2385 $partid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $oargs
2388 } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2390 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
2391 my @recs = map { $_->source } @$maps;
2393 for my $rec (@recs) {
2394 @status = _check_title_hold_is_possible(
2395 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $holdable_formats, $oargs
2401 # else { Unrecognized hold_type ! } # FIXME: return error? or 0?
2405 sub create_ranged_org_filter {
2406 my($e, $selection_ou, $depth) = @_;
2408 # find the orgs from which this hold may be fulfilled,
2409 # based on the selection_ou and depth
2411 my $top_org = $e->search_actor_org_unit([
2412 {parent_ou => undef},
2413 {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
2416 return () if $depth == $top_org->ou_type->depth;
2418 my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
2419 %org_filter = (circ_lib => []);
2420 push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
2422 $logger->info("hold org filter at depth $depth and selection_ou ".
2423 "$selection_ou created list of @{$org_filter{circ_lib}}");
2429 sub _check_title_hold_is_possible {
2430 my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $holdable_formats, $oargs ) = @_;
2432 my ($types, $formats, $lang);
2433 if (defined($holdable_formats)) {
2434 ($types, $formats, $lang) = split '-', $holdable_formats;
2437 my $e = new_editor();
2438 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2440 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2441 my $copies = $e->json_query(
2443 select => { acp => ['id', 'circ_lib'] },
2448 fkey => 'call_number',
2452 filter => { id => $titleid },
2460 ( $types ? (item_type => [split '', $types]) : () ),
2461 ( $formats ? (item_form => [split '', $formats]) : () ),
2462 ( $lang ? (item_lang => $lang) : () )
2467 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2468 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' },
2469 acpm => { field => 'target_copy', type => 'left' } # ignore part-linked copies
2473 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter },
2474 '+acpm' => { target_copy => undef } # ignore part-linked copies
2479 $logger->info("title possible found ".scalar(@$copies)." potential copies");
2483 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2484 "payload" => {"fail_part" => "no_ultimate_items"}
2489 # -----------------------------------------------------------------------
2490 # sort the copies into buckets based on their circ_lib proximity to
2491 # the patron's home_ou.
2492 # -----------------------------------------------------------------------
2494 my $home_org = $patron->home_ou;
2495 my $req_org = $request_lib->id;
2497 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2499 $prox_cache{$home_org} =
2500 $e->search_actor_org_unit_proximity({from_org => $home_org})
2501 unless $prox_cache{$home_org};
2502 my $home_prox = $prox_cache{$home_org};
2505 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2506 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2508 my @keys = sort { $a <=> $b } keys %buckets;
2511 if( $home_org ne $req_org ) {
2512 # -----------------------------------------------------------------------
2513 # shove the copies close to the request_lib into the primary buckets
2514 # directly before the farthest away copies. That way, they are not
2515 # given priority, but they are checked before the farthest copies.
2516 # -----------------------------------------------------------------------
2517 $prox_cache{$req_org} =
2518 $e->search_actor_org_unit_proximity({from_org => $req_org})
2519 unless $prox_cache{$req_org};
2520 my $req_prox = $prox_cache{$req_org};
2523 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2524 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2526 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2527 my $new_key = $highest_key - 0.5; # right before the farthest prox
2528 my @keys2 = sort { $a <=> $b } keys %buckets2;
2529 for my $key (@keys2) {
2530 last if $key >= $highest_key;
2531 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2535 @keys = sort { $a <=> $b } keys %buckets;
2540 my $age_protect_only = 0;
2541 OUTER: for my $key (@keys) {
2542 my @cps = @{$buckets{$key}};
2544 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2546 for my $copyid (@cps) {
2548 next if $seen{$copyid};
2549 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2550 my $copy = $e->retrieve_asset_copy($copyid);
2551 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2553 unless($title) { # grab the title if we don't already have it
2554 my $vol = $e->retrieve_asset_call_number(
2555 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2556 $title = $vol->record;
2559 @status = verify_copy_for_hold(
2560 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2562 $age_protect_only ||= $status[3];
2563 last OUTER if $status[0];
2567 $status[3] = $age_protect_only;
2571 sub _check_issuance_hold_is_possible {
2572 my( $issuanceid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2574 my $e = new_editor();
2575 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2577 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2578 my $copies = $e->json_query(
2580 select => { acp => ['id', 'circ_lib'] },
2586 filter => { issuance => $issuanceid }
2588 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2589 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2593 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2599 $logger->info("issuance possible found ".scalar(@$copies)." potential copies");
2603 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2604 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2609 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2610 "payload" => {"fail_part" => "no_ultimate_items"}
2618 # -----------------------------------------------------------------------
2619 # sort the copies into buckets based on their circ_lib proximity to
2620 # the patron's home_ou.
2621 # -----------------------------------------------------------------------
2623 my $home_org = $patron->home_ou;
2624 my $req_org = $request_lib->id;
2626 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2628 $prox_cache{$home_org} =
2629 $e->search_actor_org_unit_proximity({from_org => $home_org})
2630 unless $prox_cache{$home_org};
2631 my $home_prox = $prox_cache{$home_org};
2634 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2635 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2637 my @keys = sort { $a <=> $b } keys %buckets;
2640 if( $home_org ne $req_org ) {
2641 # -----------------------------------------------------------------------
2642 # shove the copies close to the request_lib into the primary buckets
2643 # directly before the farthest away copies. That way, they are not
2644 # given priority, but they are checked before the farthest copies.
2645 # -----------------------------------------------------------------------
2646 $prox_cache{$req_org} =
2647 $e->search_actor_org_unit_proximity({from_org => $req_org})
2648 unless $prox_cache{$req_org};
2649 my $req_prox = $prox_cache{$req_org};
2652 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2653 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2655 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2656 my $new_key = $highest_key - 0.5; # right before the farthest prox
2657 my @keys2 = sort { $a <=> $b } keys %buckets2;
2658 for my $key (@keys2) {
2659 last if $key >= $highest_key;
2660 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2664 @keys = sort { $a <=> $b } keys %buckets;
2669 my $age_protect_only = 0;
2670 OUTER: for my $key (@keys) {
2671 my @cps = @{$buckets{$key}};
2673 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2675 for my $copyid (@cps) {
2677 next if $seen{$copyid};
2678 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2679 my $copy = $e->retrieve_asset_copy($copyid);
2680 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2682 unless($title) { # grab the title if we don't already have it
2683 my $vol = $e->retrieve_asset_call_number(
2684 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2685 $title = $vol->record;
2688 @status = verify_copy_for_hold(
2689 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2691 $age_protect_only ||= $status[3];
2692 last OUTER if $status[0];
2697 if (!defined($empty_ok)) {
2698 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2699 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2702 return (1,0) if ($empty_ok);
2704 $status[3] = $age_protect_only;
2708 sub _check_monopart_hold_is_possible {
2709 my( $partid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2711 my $e = new_editor();
2712 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2714 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2715 my $copies = $e->json_query(
2717 select => { acp => ['id', 'circ_lib'] },
2721 field => 'target_copy',
2723 filter => { part => $partid }
2725 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2726 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2730 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2736 $logger->info("monopart possible found ".scalar(@$copies)." potential copies");
2740 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2741 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2746 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2747 "payload" => {"fail_part" => "no_ultimate_items"}
2755 # -----------------------------------------------------------------------
2756 # sort the copies into buckets based on their circ_lib proximity to
2757 # the patron's home_ou.
2758 # -----------------------------------------------------------------------
2760 my $home_org = $patron->home_ou;
2761 my $req_org = $request_lib->id;
2763 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2765 $prox_cache{$home_org} =
2766 $e->search_actor_org_unit_proximity({from_org => $home_org})
2767 unless $prox_cache{$home_org};
2768 my $home_prox = $prox_cache{$home_org};
2771 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2772 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2774 my @keys = sort { $a <=> $b } keys %buckets;
2777 if( $home_org ne $req_org ) {
2778 # -----------------------------------------------------------------------
2779 # shove the copies close to the request_lib into the primary buckets
2780 # directly before the farthest away copies. That way, they are not
2781 # given priority, but they are checked before the farthest copies.
2782 # -----------------------------------------------------------------------
2783 $prox_cache{$req_org} =
2784 $e->search_actor_org_unit_proximity({from_org => $req_org})
2785 unless $prox_cache{$req_org};
2786 my $req_prox = $prox_cache{$req_org};
2789 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2790 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2792 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2793 my $new_key = $highest_key - 0.5; # right before the farthest prox
2794 my @keys2 = sort { $a <=> $b } keys %buckets2;
2795 for my $key (@keys2) {
2796 last if $key >= $highest_key;
2797 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2801 @keys = sort { $a <=> $b } keys %buckets;
2806 my $age_protect_only = 0;
2807 OUTER: for my $key (@keys) {
2808 my @cps = @{$buckets{$key}};
2810 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2812 for my $copyid (@cps) {
2814 next if $seen{$copyid};
2815 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2816 my $copy = $e->retrieve_asset_copy($copyid);
2817 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2819 unless($title) { # grab the title if we don't already have it
2820 my $vol = $e->retrieve_asset_call_number(
2821 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2822 $title = $vol->record;
2825 @status = verify_copy_for_hold(
2826 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs);
2828 $age_protect_only ||= $status[3];
2829 last OUTER if $status[0];
2834 if (!defined($empty_ok)) {
2835 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2836 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2839 return (1,0) if ($empty_ok);
2841 $status[3] = $age_protect_only;
2846 sub _check_volume_hold_is_possible {
2847 my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $oargs ) = @_;
2848 my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
2849 my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
2850 $logger->info("checking possibility of volume hold for volume ".$vol->id);
2852 my $filter_copies = [];
2853 for my $copy (@$copies) {
2854 # ignore part-mapped copies for regular volume level holds
2855 push(@$filter_copies, $copy) unless
2856 new_editor->search_asset_copy_part_map({target_copy => $copy->id})->[0];
2858 $copies = $filter_copies;
2863 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2864 "payload" => {"fail_part" => "no_ultimate_items"}
2870 my $age_protect_only = 0;
2871 for my $copy ( @$copies ) {
2872 @status = verify_copy_for_hold(
2873 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs );
2874 $age_protect_only ||= $status[3];
2877 $status[3] = $age_protect_only;
2883 sub verify_copy_for_hold {
2884 my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib, $oargs ) = @_;
2885 $oargs = {} unless defined $oargs;
2886 $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
2887 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2888 { patron => $patron,
2889 requestor => $requestor,
2892 title_descriptor => $title->fixed_fields, # this is fleshed into the title object
2893 pickup_lib => $pickup_lib,
2894 request_lib => $request_lib,
2896 show_event_list => 1
2901 my $permit_anyway = 0;
2902 foreach my $permit_event (@$permitted) {
2903 if (grep { $_ eq $permit_event->{textcode} } @{$oargs->{events}}) {
2908 $permitted = [] if $permit_anyway;
2910 my $age_protect_only = 0;
2911 if (@$permitted == 1 && @$permitted[0]->{textcode} eq 'ITEM_AGE_PROTECTED') {
2912 $age_protect_only = 1;
2916 (not scalar @$permitted), # true if permitted is an empty arrayref
2917 ( # XXX This test is of very dubious value; someone should figure
2918 # out what if anything is checking this value
2919 ($copy->circ_lib == $pickup_lib) and
2920 ($copy->status == OILS_COPY_STATUS_AVAILABLE)
2929 sub find_nearest_permitted_hold {
2932 my $editor = shift; # CStoreEditor object
2933 my $copy = shift; # copy to target
2934 my $user = shift; # staff
2935 my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
2937 my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
2939 my $bc = $copy->barcode;
2941 # find any existing holds that already target this copy
2942 my $old_holds = $editor->search_action_hold_request(
2943 { current_copy => $copy->id,
2944 cancel_time => undef,
2945 capture_time => undef
2949 my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
2951 $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
2952 " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
2954 my $fifo = $U->ou_ancestor_setting_value($user->ws_ou, 'circ.holds_fifo');
2956 # search for what should be the best holds for this copy to fulfill
2957 my $best_holds = $U->storagereq(
2958 "open-ils.storage.action.hold_request.nearest_hold.atomic",
2959 $user->ws_ou, $copy->id, 100, $hold_stall_interval, $fifo );
2961 # Add any pre-targeted holds to the list too? Unless they are already there, anyway.
2963 for my $holdid (@$old_holds) {
2964 next unless $holdid;
2965 push(@$best_holds, $holdid) unless ( grep { ''.$holdid eq ''.$_ } @$best_holds );
2969 unless(@$best_holds) {
2970 $logger->info("circulator: no suitable holds found for copy $bc");
2971 return (undef, $evt);
2977 # for each potential hold, we have to run the permit script
2978 # to make sure the hold is actually permitted.
2981 for my $holdid (@$best_holds) {
2982 next unless $holdid;
2983 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
2985 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
2986 my $reqr = $reqr_cache{$hold->requestor} || $editor->retrieve_actor_user($hold->requestor);
2987 my $rlib = $org_cache{$hold->request_lib} || $editor->retrieve_actor_org_unit($hold->request_lib);
2989 $reqr_cache{$hold->requestor} = $reqr;
2990 $org_cache{$hold->request_lib} = $rlib;
2992 # see if this hold is permitted
2993 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2994 { patron_id => $hold->usr,
2997 pickup_lib => $hold->pickup_lib,
2998 request_lib => $rlib,
3010 unless( $best_hold ) { # no "good" permitted holds were found
3012 $logger->info("circulator: no suitable holds found for copy $bc");
3013 return (undef, $evt);
3016 $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
3018 # indicate a permitted hold was found
3019 return $best_hold if $check_only;
3021 # we've found a permitted hold. we need to "grab" the copy
3022 # to prevent re-targeted holds (next part) from re-grabbing the copy
3023 $best_hold->current_copy($copy->id);
3024 $editor->update_action_hold_request($best_hold)
3025 or return (undef, $editor->event);
3030 # re-target any other holds that already target this copy
3031 for my $old_hold (@$old_holds) {
3032 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
3033 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
3034 $old_hold->id." after a better hold [".$best_hold->id."] was found");
3035 $old_hold->clear_current_copy;
3036 $old_hold->clear_prev_check_time;
3037 $editor->update_action_hold_request($old_hold)
3038 or return (undef, $editor->event);
3039 push(@retarget, $old_hold->id);
3042 return ($best_hold, undef, (@retarget) ? \@retarget : undef);
3050 __PACKAGE__->register_method(
3051 method => 'all_rec_holds',
3052 api_name => 'open-ils.circ.holds.retrieve_all_from_title',
3056 my( $self, $conn, $auth, $title_id, $args ) = @_;
3058 my $e = new_editor(authtoken=>$auth);
3059 $e->checkauth or return $e->event;
3060 $e->allowed('VIEW_HOLD') or return $e->event;
3063 $args->{fulfillment_time} = undef; # we don't want to see old fulfilled holds
3064 $args->{cancel_time} = undef;
3066 my $resp = { volume_holds => [], copy_holds => [], recall_holds => [], force_holds => [], metarecord_holds => [], part_holds => [], issuance_holds => [] };
3068 my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
3070 $resp->{metarecord_holds} = $e->search_action_hold_request(
3071 { hold_type => OILS_HOLD_TYPE_METARECORD,
3072 target => $mr_map->metarecord,
3078 $resp->{title_holds} = $e->search_action_hold_request(
3080 hold_type => OILS_HOLD_TYPE_TITLE,
3081 target => $title_id,
3085 my $parts = $e->search_biblio_monograph_part(
3091 $resp->{part_holds} = $e->search_action_hold_request(
3093 hold_type => OILS_HOLD_TYPE_MONOPART,
3099 my $subs = $e->search_serial_subscription(
3100 { record_entry => $title_id }, {idlist=>1});
3103 my $issuances = $e->search_serial_issuance(
3104 {subscription => $subs}, {idlist=>1}
3108 $resp->{issuance_holds} = $e->search_action_hold_request(
3110 hold_type => OILS_HOLD_TYPE_ISSUANCE,
3111 target => $issuances,
3118 my $vols = $e->search_asset_call_number(
3119 { record => $title_id, deleted => 'f' }, {idlist=>1});
3121 return $resp unless @$vols;
3123 $resp->{volume_holds} = $e->search_action_hold_request(
3125 hold_type => OILS_HOLD_TYPE_VOLUME,
3130 my $copies = $e->search_asset_copy(
3131 { call_number => $vols, deleted => 'f' }, {idlist=>1});
3133 return $resp unless @$copies;
3135 $resp->{copy_holds} = $e->search_action_hold_request(
3137 hold_type => OILS_HOLD_TYPE_COPY,
3142 $resp->{recall_holds} = $e->search_action_hold_request(
3144 hold_type => OILS_HOLD_TYPE_RECALL,
3149 $resp->{force_holds} = $e->search_action_hold_request(
3151 hold_type => OILS_HOLD_TYPE_FORCE,
3163 __PACKAGE__->register_method(
3164 method => 'uber_hold',
3166 api_name => 'open-ils.circ.hold.details.retrieve'
3170 my($self, $client, $auth, $hold_id, $args) = @_;
3171 my $e = new_editor(authtoken=>$auth);
3172 $e->checkauth or return $e->event;
3173 return uber_hold_impl($e, $hold_id, $args);
3176 __PACKAGE__->register_method(
3177 method => 'batch_uber_hold',
3180 api_name => 'open-ils.circ.hold.details.batch.retrieve'
3183 sub batch_uber_hold {
3184 my($self, $client, $auth, $hold_ids, $args) = @_;
3185 my $e = new_editor(authtoken=>$auth);
3186 $e->checkauth or return $e->event;
3187 $client->respond(uber_hold_impl($e, $_, $args)) for @$hold_ids;
3191 sub uber_hold_impl {
3192 my($e, $hold_id, $args) = @_;
3195 my $hold = $e->retrieve_action_hold_request(
3200 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
3203 ) or return $e->event;
3205 if($hold->usr->id ne $e->requestor->id) {
3206 # A user is allowed to see his/her own holds
3207 $e->allowed('VIEW_HOLD') or return $e->event;
3208 $hold->notes( # filter out any non-staff ("private") notes
3209 [ grep { !$U->is_true($_->staff) } @{$hold->notes} ] );
3212 # caller is asking for own hold, but may not have permission to view staff notes
3213 unless($e->allowed('VIEW_HOLD')) {
3214 $hold->notes( # filter out any staff notes
3215 [ grep { $U->is_true($_->staff) } @{$hold->notes} ] );
3219 my $user = $hold->usr;
3220 $hold->usr($user->id);
3223 my( $mvr, $volume, $copy, $issuance, $part, $bre ) = find_hold_mvr($e, $hold, $args->{suppress_mvr});
3225 flesh_hold_notices([$hold], $e) unless $args->{suppress_notices};
3226 flesh_hold_transits([$hold]) unless $args->{suppress_transits};
3228 my $details = retrieve_hold_queue_status_impl($e, $hold);
3233 ($copy ? (copy => $copy) : ()),
3234 ($volume ? (volume => $volume) : ()),
3235 ($issuance ? (issuance => $issuance) : ()),
3236 ($part ? (part => $part) : ()),
3237 ($args->{include_bre} ? (bre => $bre) : ()),
3238 ($args->{suppress_mvr} ? () : (mvr => $mvr)),
3242 unless($args->{suppress_patron_details}) {
3243 my $card = $e->retrieve_actor_card($user->card) or return $e->event;
3244 $resp->{patron_first} = $user->first_given_name,
3245 $resp->{patron_last} = $user->family_name,
3246 $resp->{patron_barcode} = $card->barcode,
3247 $resp->{patron_alias} = $user->alias,
3255 # -----------------------------------------------------
3256 # Returns the MVR object that represents what the
3258 # -----------------------------------------------------
3260 my( $e, $hold, $no_mvr ) = @_;
3268 if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
3269 my $mr = $e->retrieve_metabib_metarecord($hold->target)
3270 or return $e->event;
3271 $tid = $mr->master_record;
3273 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
3274 $tid = $hold->target;
3276 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
3277 $volume = $e->retrieve_asset_call_number($hold->target)
3278 or return $e->event;
3279 $tid = $volume->record;
3281 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
3282 $issuance = $e->retrieve_serial_issuance([
3284 {flesh => 1, flesh_fields => {siss => [ qw/subscription/ ]}}
3285 ]) or return $e->event;
3287 $tid = $issuance->subscription->record_entry;
3289 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_MONOPART ) {
3290 $part = $e->retrieve_biblio_monograph_part([
3292 ]) or return $e->event;
3294 $tid = $part->record;
3296 } 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 ) {
3297 $copy = $e->retrieve_asset_copy([
3299 {flesh => 1, flesh_fields => {acp => ['call_number']}}
3300 ]) or return $e->event;
3302 $volume = $copy->call_number;
3303 $tid = $volume->record;
3306 if(!$copy and ref $hold->current_copy ) {
3307 $copy = $hold->current_copy;
3308 $hold->current_copy($copy->id);
3311 if(!$volume and $copy) {
3312 $volume = $e->retrieve_asset_call_number($copy->call_number);
3315 # TODO return metarcord mvr for M holds
3316 my $title = $e->retrieve_biblio_record_entry($tid);
3317 return ( ($no_mvr) ? undef : $U->record_to_mvr($title), $volume, $copy, $issuance, $part, $title );
3320 __PACKAGE__->register_method(
3321 method => 'clear_shelf_cache',
3322 api_name => 'open-ils.circ.hold.clear_shelf.get_cache',
3326 Returns the holds processed with the given cache key
3331 sub clear_shelf_cache {
3332 my($self, $client, $auth, $cache_key, $chunk_size) = @_;
3333 my $e = new_editor(authtoken => $auth, xact => 1);
3334 return $e->die_event unless $e->checkauth and $e->allowed('VIEW_HOLD');
3337 my $hold_data = OpenSRF::Utils::Cache->new('global')->get_cache($cache_key);
3340 $logger->info("no hold data found in cache"); # XXX TODO return event
3346 foreach (keys %$hold_data) {
3347 $maximum += scalar(@{ $hold_data->{$_} });
3349 $client->respond({"maximum" => $maximum, "progress" => 0});
3351 for my $action (sort keys %$hold_data) {
3352 while (@{$hold_data->{$action}}) {
3353 my @hid_chunk = splice @{$hold_data->{$action}}, 0, $chunk_size;
3355 my $result_chunk = $e->json_query({
3357 "acp" => ["barcode"],
3359 first_given_name second_given_name family_name alias
3362 "acnp" => [{column => "label", alias => "prefix"}],
3363 "acns" => [{column => "label", alias => "suffix"}],
3371 "field" => "id", "fkey" => "current_copy",
3374 "field" => "id", "fkey" => "call_number",
3377 "field" => "id", "fkey" => "record"
3380 "field" => "id", "fkey" => "prefix"
3383 "field" => "id", "fkey" => "suffix"
3387 "acpl" => {"field" => "id", "fkey" => "location"}
3390 "au" => {"field" => "id", "fkey" => "usr"}
3393 "where" => {"+ahr" => {"id" => \@hid_chunk}}
3394 }, {"substream" => 1}) or return $e->die_event;
3398 +{"action" => $action, "hold_details" => $_}
3409 __PACKAGE__->register_method(
3410 method => 'clear_shelf_process',
3412 api_name => 'open-ils.circ.hold.clear_shelf.process',
3415 1. Find all holds that have expired on the holds shelf
3417 3. If a clear-shelf status is configured, put targeted copies into this status
3418 4. Divide copies into 3 groups: items to transit, items to reshelve, and items
3419 that are needed for holds. No subsequent action is taken on the holds
3420 or items after grouping.
3425 sub clear_shelf_process {
3426 my($self, $client, $auth, $org_id, $match_copy) = @_;
3428 my $e = new_editor(authtoken=>$auth, xact => 1);
3429 $e->checkauth or return $e->die_event;
3430 my $cache = OpenSRF::Utils::Cache->new('global');
3432 $org_id ||= $e->requestor->ws_ou;
3433 $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
3435 my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
3437 my @hold_ids = $self->method_lookup(
3438 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
3439 )->run($auth, $org_id, $match_copy);
3442 my @canceled_holds; # newly canceled holds
3443 my $chunk_size = 25; # chunked status updates
3445 for my $hold_id (@hold_ids) {
3447 $logger->info("Clear shelf processing hold $hold_id");
3449 my $hold = $e->retrieve_action_hold_request([
3452 flesh_fields => {ahr => ['current_copy']}
3456 if (!$hold->cancel_time) { # may be canceled but still on the holds shelf
3457 $hold->cancel_time('now');
3458 $hold->cancel_cause(2); # Hold Shelf expiration
3459 $e->update_action_hold_request($hold) or return $e->die_event;
3460 delete_hold_copy_maps($self, $e, $hold->id) and return $e->die_event;
3461 push(@canceled_holds, $hold_id);
3464 my $copy = $hold->current_copy;
3466 if($copy_status or $copy_status == 0) {
3467 # if a clear-shelf copy status is defined, update the copy
3468 $copy->status($copy_status);
3469 $copy->edit_date('now');
3470 $copy->editor($e->requestor->id);
3471 $e->update_asset_copy($copy) or return $e->die_event;
3474 push(@holds, $hold);
3475 $client->respond({maximum => scalar(@holds), progress => $counter}) if ( (++$counter % $chunk_size) == 0);
3486 for my $hold (@holds) {
3488 my $copy = $hold->current_copy;
3489 my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
3491 if($alt_hold and !$match_copy) {
3493 push(@{$cache_data{hold}}, $hold->id); # copy is needed for a hold
3495 } elsif($copy->circ_lib != $e->requestor->ws_ou) {
3497 push(@{$cache_data{transit}}, $hold->id); # copy needs to transit
3501 push(@{$cache_data{shelf}}, $hold->id); # copy needs to go back to the shelf
3505 my $cache_key = md5_hex(time . $$ . rand());
3506 $logger->info("clear_shelf_cache: storing under $cache_key");
3507 $cache->put_cache($cache_key, \%cache_data, 7200); # TODO: 2 hours. configurable?
3509 # tell the client we're done
3510 $client->respond_complete({cache_key => $cache_key});
3513 # fire off the hold cancelation trigger and wait for response so don't flood the service
3515 # refetch the holds to pick up the caclulated cancel_time,
3516 # which may be needed by Action/Trigger
3518 my $updated_holds = [];
3519 $updated_holds = $e->search_action_hold_request({id => \@canceled_holds}, {substream => 1}) if (@canceled_holds > 0);
3522 $U->create_events_for_hook(
3523 'hold_request.cancel.expire_holds_shelf',
3524 $_, $org_id, undef, undef, 1) for @$updated_holds;
3527 # tell the client we're done
3528 $client->respond_complete;
3532 __PACKAGE__->register_method(
3533 method => 'usr_hold_summary',
3534 api_name => 'open-ils.circ.holds.user_summary',
3536 Returns a summary of holds statuses for a given user
3540 sub usr_hold_summary {
3541 my($self, $conn, $auth, $user_id) = @_;
3543 my $e = new_editor(authtoken=>$auth);
3544 $e->checkauth or return $e->event;
3545 $e->allowed('VIEW_HOLD') or return $e->event;
3547 my $holds = $e->search_action_hold_request(
3550 fulfillment_time => undef,
3551 cancel_time => undef,
3555 my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
3556 $summary{_hold_status($e, $_)} += 1 for @$holds;
3562 __PACKAGE__->register_method(
3563 method => 'hold_has_copy_at',
3564 api_name => 'open-ils.circ.hold.has_copy_at',
3567 'Returns the ID of the found copy and name of the shelving location if there is ' .
3568 'an available copy at the specified org unit. Returns empty hash otherwise. ' .
3569 'The anticipated use for this method is to determine whether an item is ' .
3570 'available at the library where the user is placing the hold (or, alternatively, '.
3571 'at the pickup library) to encourage bypassing the hold placement and just ' .
3572 'checking out the item.' ,
3574 { desc => 'Authentication Token', type => 'string' },
3575 { desc => 'Method Arguments. Options include: hold_type, hold_target, org_unit. '
3576 . 'hold_type is the hold type code (T, V, C, M, ...). '
3577 . 'hold_target is the identifier of the hold target object. '
3578 . 'org_unit is org unit ID.',
3583 desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
3589 sub hold_has_copy_at {
3590 my($self, $conn, $auth, $args) = @_;
3592 my $e = new_editor(authtoken=>$auth);
3593 $e->checkauth or return $e->event;
3595 my $hold_type = $$args{hold_type};
3596 my $hold_target = $$args{hold_target};
3597 my $org_unit = $$args{org_unit};
3600 select => {acp => ['id'], acpl => ['name']},
3603 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
3604 ccs => {field => 'id', filter => { holdable => 't'}, fkey => 'status' }
3607 where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit, status => [0,7]}},
3611 if($hold_type eq 'C' or $hold_type eq 'F' or $hold_type eq 'R') {
3613 $query->{where}->{'+acp'}->{id} = $hold_target;
3615 } elsif($hold_type eq 'V') {
3617 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3619 } elsif($hold_type eq 'P') {
3621 $query->{from}->{acp}->{acpm} = {
3622 field => 'target_copy',
3624 filter => {part => $hold_target},
3627 } elsif($hold_type eq 'I') {
3629 $query->{from}->{acp}->{sitem} = {
3632 filter => {issuance => $hold_target},
3635 } elsif($hold_type eq 'T') {
3637 $query->{from}->{acp}->{acn} = {
3639 fkey => 'call_number',
3643 filter => {id => $hold_target},
3651 $query->{from}->{acp}->{acn} = {
3653 fkey => 'call_number',
3662 filter => {metarecord => $hold_target},
3670 my $res = $e->json_query($query)->[0] or return {};
3671 return {copy => $res->{id}, location => $res->{name}} if $res;
3675 # returns true if the user already has an item checked out
3676 # that could be used to fulfill the requested hold.
3677 sub hold_item_is_checked_out {
3678 my($e, $user_id, $hold_type, $hold_target) = @_;
3681 select => {acp => ['id']},
3682 from => {acp => {}},
3686 in => { # copies for circs the user has checked out
3687 select => {circ => ['target_copy']},
3691 checkin_time => undef,
3693 {stop_fines => ["MAXFINES","LONGOVERDUE"]},
3694 {stop_fines => undef}
3704 if($hold_type eq 'C' || $hold_type eq 'R' || $hold_type eq 'F') {
3706 $query->{where}->{'+acp'}->{id}->{in}->{where}->{'target_copy'} = $hold_target;
3708 } elsif($hold_type eq 'V') {
3710 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3712 } elsif($hold_type eq 'P') {
3714 $query->{from}->{acp}->{acpm} = {
3715 field => 'target_copy',
3717 filter => {part => $hold_target},
3720 } elsif($hold_type eq 'I') {
3722 $query->{from}->{acp}->{sitem} = {
3725 filter => {issuance => $hold_target},
3728 } elsif($hold_type eq 'T') {
3730 $query->{from}->{acp}->{acn} = {
3732 fkey => 'call_number',
3736 filter => {id => $hold_target},
3744 $query->{from}->{acp}->{acn} = {
3746 fkey => 'call_number',
3755 filter => {metarecord => $hold_target},
3763 return $e->json_query($query)->[0];
3766 __PACKAGE__->register_method(
3767 method => 'change_hold_title',
3768 api_name => 'open-ils.circ.hold.change_title',
3771 Updates all title level holds targeting the specified bibs to point a new bib./,
3773 { desc => 'Authentication Token', type => 'string' },
3774 { desc => 'New Target Bib Id', type => 'number' },
3775 { desc => 'Old Target Bib Ids', type => 'array' },
3777 return => { desc => '1 on success' }
3781 __PACKAGE__->register_method(
3782 method => 'change_hold_title_for_specific_holds',
3783 api_name => 'open-ils.circ.hold.change_title.specific_holds',
3786 Updates specified holds to target new bib./,
3788 { desc => 'Authentication Token', type => 'string' },
3789 { desc => 'New Target Bib Id', type => 'number' },
3790 { desc => 'Holds Ids for holds to update', type => 'array' },
3792 return => { desc => '1 on success' }
3797 sub change_hold_title {
3798 my( $self, $client, $auth, $new_bib_id, $bib_ids ) = @_;
3800 my $e = new_editor(authtoken=>$auth, xact=>1);
3801 return $e->die_event unless $e->checkauth;
3803 my $holds = $e->search_action_hold_request(
3806 cancel_time => undef,
3807 fulfillment_time => undef,
3813 flesh_fields => { ahr => ['usr'] }
3819 for my $hold (@$holds) {
3820 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3821 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3822 $hold->target( $new_bib_id );
3823 $e->update_action_hold_request($hold) or return $e->die_event;
3828 _reset_hold($self, $e->requestor, $_) for @$holds;
3833 sub change_hold_title_for_specific_holds {
3834 my( $self, $client, $auth, $new_bib_id, $hold_ids ) = @_;
3836 my $e = new_editor(authtoken=>$auth, xact=>1);
3837 return $e->die_event unless $e->checkauth;
3839 my $holds = $e->search_action_hold_request(
3842 cancel_time => undef,
3843 fulfillment_time => undef,
3849 flesh_fields => { ahr => ['usr'] }
3855 for my $hold (@$holds) {
3856 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3857 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3858 $hold->target( $new_bib_id );
3859 $e->update_action_hold_request($hold) or return $e->die_event;
3864 _reset_hold($self, $e->requestor, $_) for @$holds;
3869 __PACKAGE__->register_method(
3870 method => 'rec_hold_count',
3871 api_name => 'open-ils.circ.bre.holds.count',
3873 desc => q/Returns the total number of holds that target the
3874 selected bib record or its associated copies and call_numbers/,
3876 { desc => 'Bib ID', type => 'number' },
3878 return => {desc => 'Hold count', type => 'number'}
3882 __PACKAGE__->register_method(
3883 method => 'rec_hold_count',
3884 api_name => 'open-ils.circ.mmr.holds.count',
3886 desc => q/Returns the total number of holds that target the
3887 selected metarecord or its associated copies, call_numbers, and bib records/,
3889 { desc => 'Metarecord ID', type => 'number' },
3891 return => {desc => 'Hold count', type => 'number'}
3895 # XXX Need to add type I (and, soon, type P) holds to these counts
3896 sub rec_hold_count {
3897 my($self, $conn, $target_id) = @_;
3904 filter => {metarecord => $target_id}
3911 filter => { id => $target_id },
3916 if($self->api_name =~ /mmr/) {
3917 delete $bre_join->{bre}->{filter};
3918 $bre_join->{bre}->{join} = $mmr_join;
3924 fkey => 'call_number',
3930 select => {ahr => [{column => 'id', transform => 'count', alias => 'count'}]},
3934 cancel_time => undef,
3935 fulfillment_time => undef,
3939 hold_type => [qw/C F R/],
3942 select => {acp => ['id']},
3943 from => { acp => $cn_join }
3953 select => {acn => ['id']},
3954 from => {acn => $bre_join}
3962 target => $target_id
3970 if($self->api_name =~ /mmr/) {
3971 $query->{where}->{'+ahr'}->{'-or'}->[2] = {
3976 select => {bre => ['id']},
3977 from => {bre => $mmr_join}
3983 $query->{where}->{'+ahr'}->{'-or'}->[3] = {
3986 target => $target_id
3992 return new_editor()->json_query($query)->[0]->{count};
3995 # A helper function to calculate a hold's expiration time at a given
3996 # org_unit. Takes the org_unit as an argument and returns either the
3997 # hold expire time as an ISO8601 string or undef if there is no hold
3998 # expiration interval set for the subject ou.
3999 sub calculate_expire_time
4002 my $interval = $U->ou_ancestor_setting_value($ou, OILS_SETTING_HOLD_EXPIRE);
4004 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
4005 return $U->epoch2ISO8601($date->epoch);