1 # ---------------------------------------------------------------
2 # Copyright (C) 2005 Georgia Public Library Service
3 # Bill Erickson <highfalutin@gmail.com>
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 # ---------------------------------------------------------------
17 package OpenILS::Application::Circ::Holds;
18 use base qw/OpenILS::Application/;
19 use strict; use warnings;
20 use OpenILS::Application::AppUtils;
23 use OpenSRF::EX qw(:try);
27 use OpenSRF::Utils::Logger qw(:logger);
28 use OpenILS::Utils::CStoreEditor q/:funcs/;
29 use OpenILS::Utils::PermitHold;
30 use OpenSRF::Utils::SettingsClient;
31 use OpenILS::Const qw/:const/;
32 use OpenILS::Application::Circ::Transit;
33 use OpenILS::Application::Actor::Friends;
35 use DateTime::Format::ISO8601;
36 use OpenSRF::Utils qw/:datetime/;
37 use Digest::MD5 qw(md5_hex);
38 use OpenSRF::Utils::Cache;
39 my $apputils = "OpenILS::Application::AppUtils";
43 __PACKAGE__->register_method(
44 method => "create_hold_batch",
45 api_name => "open-ils.circ.holds.create.batch",
48 desc => q/@see open-ils.circ.holds.create.batch/,
50 { desc => 'Authentication token', type => 'string' },
51 { desc => 'Array of hold objects', type => 'array' }
54 desc => 'Array of hold ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
59 __PACKAGE__->register_method(
60 method => "create_hold_batch",
61 api_name => "open-ils.circ.holds.create.override.batch",
64 desc => '@see open-ils.circ.holds.create.batch',
69 sub create_hold_batch {
70 my( $self, $conn, $auth, $hold_list ) = @_;
71 (my $method = $self->api_name) =~ s/\.batch//og;
72 foreach (@$hold_list) {
73 my ($res) = $self->method_lookup($method)->run($auth, $_);
80 __PACKAGE__->register_method(
81 method => "create_hold",
82 api_name => "open-ils.circ.holds.create",
84 desc => "Create a new hold for an item. From a permissions perspective, " .
85 "the login session is used as the 'requestor' of the hold. " .
86 "The hold recipient is determined by the 'usr' setting within the hold object. " .
87 'First we verify the requestor has holds request permissions. ' .
88 'Then we verify that the recipient is allowed to make the given hold. ' .
89 'If not, we see if the requestor has "override" capabilities. If not, ' .
90 'a permission exception is returned. If permissions allow, we cycle ' .
91 'through the set of holds objects and create. ' .
92 'If the recipient does not have permission to place multiple holds ' .
93 'on a single title and said operation is attempted, a permission ' .
94 'exception is returned',
96 { desc => 'Authentication token', type => 'string' },
97 { desc => 'Hold object for hold to be created',
98 type => 'object', class => 'ahr' }
101 desc => 'New ahr ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
106 __PACKAGE__->register_method(
107 method => "create_hold",
108 api_name => "open-ils.circ.holds.create.override",
109 notes => '@see open-ils.circ.holds.create',
111 desc => "If the recipient is not allowed to receive the requested hold, " .
112 "call this method to attempt the override",
114 { desc => 'Authentication token', type => 'string' },
116 desc => 'Hold object for hold to be created',
117 type => 'object', class => 'ahr'
121 desc => 'New hold (ahr) ID on success, -1 on missing arg, event (or ref to array of events) on error(s)',
127 my( $self, $conn, $auth, $hold ) = @_;
128 return -1 unless $hold;
129 my $e = new_editor(authtoken=>$auth, xact=>1);
130 return $e->die_event unless $e->checkauth;
132 my $override = 1 if $self->api_name =~ /override/;
136 my $requestor = $e->requestor;
137 my $recipient = $requestor;
139 if( $requestor->id ne $hold->usr ) {
140 # Make sure the requestor is allowed to place holds for
141 # the recipient if they are not the same people
142 $recipient = $e->retrieve_actor_user($hold->usr) or return $e->die_event;
143 $e->allowed('REQUEST_HOLDS', $recipient->home_ou) or return $e->die_event;
146 # If the related org setting tells us to, block if patron privs have expired
147 my $expire_setting = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_BLOCK_HOLD_FOR_EXPIRED_PATRON);
148 if ($expire_setting) {
149 my $expire = DateTime::Format::ISO8601->new->parse_datetime(
150 cleanse_ISO8601($recipient->expire_date));
152 push( @events, OpenILS::Event->new(
153 'PATRON_ACCOUNT_EXPIRED',
154 "payload" => {"fail_part" => "actor.usr.privs_expired"}
155 )) if( CORE::time > $expire->epoch ) ;
158 # Now make sure the recipient is allowed to receive the specified hold
159 my $porg = $recipient->home_ou;
160 my $rid = $e->requestor->id;
161 my $t = $hold->hold_type;
163 # See if a duplicate hold already exists
165 usr => $recipient->id,
167 fulfillment_time => undef,
168 target => $hold->target,
169 cancel_time => undef,
172 $sargs->{holdable_formats} = $hold->holdable_formats if $t eq 'M';
174 my $existing = $e->search_action_hold_request($sargs);
175 push( @events, OpenILS::Event->new('HOLD_EXISTS')) if @$existing;
177 my $checked_out = hold_item_is_checked_out($e, $recipient->id, $hold->hold_type, $hold->target);
178 push( @events, OpenILS::Event->new('HOLD_ITEM_CHECKED_OUT')) if $checked_out;
180 if ( $t eq OILS_HOLD_TYPE_METARECORD ) {
181 return $e->die_event unless $e->allowed('MR_HOLDS', $porg);
182 } elsif ( $t eq OILS_HOLD_TYPE_TITLE ) {
183 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
184 } elsif ( $t eq OILS_HOLD_TYPE_VOLUME ) {
185 return $e->die_event unless $e->allowed('VOLUME_HOLDS', $porg);
186 } elsif ( $t eq OILS_HOLD_TYPE_MONOPART ) {
187 return $e->die_event unless $e->allowed('TITLE_HOLDS', $porg);
188 } elsif ( $t eq OILS_HOLD_TYPE_ISSUANCE ) {
189 return $e->die_event unless $e->allowed('ISSUANCE_HOLDS', $porg);
190 } elsif ( $t eq OILS_HOLD_TYPE_COPY ) {
191 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
192 } elsif ( $t eq OILS_HOLD_TYPE_FORCE ) {
193 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
194 } elsif ( $t eq OILS_HOLD_TYPE_RECALL ) {
195 return $e->die_event unless $e->allowed('COPY_HOLDS', $porg);
203 for my $evt (@events) {
205 my $name = $evt->{textcode};
206 return $e->die_event unless $e->allowed("$name.override", $porg);
210 # set the configured expire time
211 unless($hold->expire_time) {
212 my $interval = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_HOLD_EXPIRE);
214 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
215 $hold->expire_time($U->epoch2ISO8601($date->epoch));
219 $hold->requestor($e->requestor->id);
220 $hold->request_lib($e->requestor->ws_ou);
221 $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
222 $hold = $e->create_action_hold_request($hold) or return $e->die_event;
226 $conn->respond_complete($hold->id);
229 'open-ils.storage.action.hold_request.copy_targeter',
230 undef, $hold->id ) unless $U->is_true($hold->frozen);
235 # makes sure that a user has permission to place the type of requested hold
236 # returns the Perm exception if not allowed, returns undef if all is well
237 sub _check_holds_perm {
238 my($type, $user_id, $org_id) = @_;
242 $evt = $apputils->check_perms($user_id, $org_id, "MR_HOLDS" );
243 } elsif ($type eq "T") {
244 $evt = $apputils->check_perms($user_id, $org_id, "TITLE_HOLDS" );
245 } elsif($type eq "V") {
246 $evt = $apputils->check_perms($user_id, $org_id, "VOLUME_HOLDS");
247 } elsif($type eq "C") {
248 $evt = $apputils->check_perms($user_id, $org_id, "COPY_HOLDS" );
255 # tests if the given user is allowed to place holds on another's behalf
256 sub _check_request_holds_perm {
259 if (my $evt = $apputils->check_perms(
260 $user_id, $org_id, "REQUEST_HOLDS")) {
265 my $ses_is_req_note = 'The login session is the requestor. If the requestor is different from the user, ' .
266 'then the requestor must have VIEW_HOLD permissions';
268 __PACKAGE__->register_method(
269 method => "retrieve_holds_by_id",
270 api_name => "open-ils.circ.holds.retrieve_by_id",
272 desc => "Retrieve the hold, with hold transits attached, for the specified ID. $ses_is_req_note",
274 { desc => 'Authentication token', type => 'string' },
275 { desc => 'Hold ID', type => 'number' }
278 desc => 'Hold object with transits attached, event on error',
284 sub retrieve_holds_by_id {
285 my($self, $client, $auth, $hold_id) = @_;
286 my $e = new_editor(authtoken=>$auth);
287 $e->checkauth or return $e->event;
288 $e->allowed('VIEW_HOLD') or return $e->event;
290 my $holds = $e->search_action_hold_request(
292 { id => $hold_id , fulfillment_time => undef },
294 order_by => { ahr => "request_time" },
296 flesh_fields => {ahr => ['notes']}
301 flesh_hold_transits($holds);
302 flesh_hold_notices($holds, $e);
307 __PACKAGE__->register_method(
308 method => "retrieve_holds",
309 api_name => "open-ils.circ.holds.retrieve",
311 desc => "Retrieves all the holds, with hold transits attached, for the specified user. $ses_is_req_note",
313 { desc => 'Authentication token', type => 'string' },
314 { desc => 'User ID', type => 'integer' }
317 desc => 'list of holds, event on error',
322 __PACKAGE__->register_method(
323 method => "retrieve_holds",
324 api_name => "open-ils.circ.holds.id_list.retrieve",
327 desc => "Retrieves all the hold IDs, for the specified user. $ses_is_req_note",
329 { desc => 'Authentication token', type => 'string' },
330 { desc => 'User ID', type => 'integer' }
333 desc => 'list of holds, event on error',
338 __PACKAGE__->register_method(
339 method => "retrieve_holds",
340 api_name => "open-ils.circ.holds.canceled.retrieve",
343 desc => "Retrieves all the cancelled holds for the specified user. $ses_is_req_note",
345 { desc => 'Authentication token', type => 'string' },
346 { desc => 'User ID', type => 'integer' }
349 desc => 'list of holds, event on error',
354 __PACKAGE__->register_method(
355 method => "retrieve_holds",
356 api_name => "open-ils.circ.holds.canceled.id_list.retrieve",
359 desc => "Retrieves list of cancelled hold IDs for the specified user. $ses_is_req_note",
361 { desc => 'Authentication token', type => 'string' },
362 { desc => 'User ID', type => 'integer' }
365 desc => 'list of hold IDs, event on error',
372 my ($self, $client, $auth, $user_id) = @_;
374 my $e = new_editor(authtoken=>$auth);
375 return $e->event unless $e->checkauth;
376 $user_id = $e->requestor->id unless defined $user_id;
378 my $notes_filter = {staff => 'f'};
379 my $user = $e->retrieve_actor_user($user_id) or return $e->event;
380 unless($user_id == $e->requestor->id) {
381 if($e->allowed('VIEW_HOLD', $user->home_ou)) {
382 $notes_filter = {staff => 't'}
384 my $allowed = OpenILS::Application::Actor::Friends->friend_perm_allowed(
385 $e, $user_id, $e->requestor->id, 'hold.view');
386 return $e->event unless $allowed;
389 # staff member looking at his/her own holds can see staff and non-staff notes
390 $notes_filter = {} if $e->allowed('VIEW_HOLD', $user->home_ou);
394 select => {ahr => ['id']},
396 where => {usr => $user_id, fulfillment_time => undef}
399 if($self->api_name =~ /canceled/) {
401 # Fetch the canceled holds
402 # order cancelled holds by cancel time, most recent first
404 $holds_query->{order_by} = [{class => 'ahr', field => 'cancel_time', direction => 'desc'}];
407 my $cancel_count = $U->ou_ancestor_setting_value(
408 $e->requestor->ws_ou, 'circ.holds.canceled.display_count', $e);
410 unless($cancel_count) {
411 $cancel_age = $U->ou_ancestor_setting_value(
412 $e->requestor->ws_ou, 'circ.holds.canceled.display_age', $e);
414 # if no settings are defined, default to last 10 cancelled holds
415 $cancel_count = 10 unless $cancel_age;
418 if($cancel_count) { # limit by count
420 $holds_query->{where}->{cancel_time} = {'!=' => undef};
421 $holds_query->{limit} = $cancel_count;
423 } elsif($cancel_age) { # limit by age
425 # find all of the canceled holds that were canceled within the configured time frame
426 my $date = DateTime->now->subtract(seconds => OpenSRF::Utils::interval_to_seconds($cancel_age));
427 $date = $U->epoch2ISO8601($date->epoch);
428 $holds_query->{where}->{cancel_time} = {'>=' => $date};
433 # order non-cancelled holds by ready-for-pickup, then active, followed by suspended
434 $holds_query->{order_by} = {ahr => ['shelf_time', 'frozen', 'request_time']};
435 $holds_query->{where}->{cancel_time} = undef;
438 my $hold_ids = $e->json_query($holds_query);
439 $hold_ids = [ map { $_->{id} } @$hold_ids ];
441 return $hold_ids if $self->api_name =~ /id_list/;
444 for my $hold_id ( @$hold_ids ) {
446 my $hold = $e->retrieve_action_hold_request($hold_id);
447 $hold->notes($e->search_action_hold_request_note({hold => $hold_id, %$notes_filter}));
450 $e->search_action_hold_transit_copy([
452 {order_by => {ahtc => 'source_send_time desc'}, limit => 1}])->[0]
462 __PACKAGE__->register_method(
463 method => 'user_hold_count',
464 api_name => 'open-ils.circ.hold.user.count'
467 sub user_hold_count {
468 my ( $self, $conn, $auth, $userid ) = @_;
469 my $e = new_editor( authtoken => $auth );
470 return $e->event unless $e->checkauth;
471 my $patron = $e->retrieve_actor_user($userid)
473 return $e->event unless $e->allowed( 'VIEW_HOLD', $patron->home_ou );
474 return __user_hold_count( $self, $e, $userid );
477 sub __user_hold_count {
478 my ( $self, $e, $userid ) = @_;
479 my $holds = $e->search_action_hold_request(
482 fulfillment_time => undef,
483 cancel_time => undef,
488 return scalar(@$holds);
492 __PACKAGE__->register_method(
493 method => "retrieve_holds_by_pickup_lib",
494 api_name => "open-ils.circ.holds.retrieve_by_pickup_lib",
496 "Retrieves all the holds, with hold transits attached, for the specified pickup_ou id."
499 __PACKAGE__->register_method(
500 method => "retrieve_holds_by_pickup_lib",
501 api_name => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
502 notes => "Retrieves all the hold ids for the specified pickup_ou id. "
505 sub retrieve_holds_by_pickup_lib {
506 my ($self, $client, $login_session, $ou_id) = @_;
508 #FIXME -- put an appropriate permission check here
509 #my( $user, $target, $evt ) = $apputils->checkses_requestor(
510 # $login_session, $user_id, 'VIEW_HOLD' );
511 #return $evt if $evt;
513 my $holds = $apputils->simplereq(
515 "open-ils.cstore.direct.action.hold_request.search.atomic",
517 pickup_lib => $ou_id ,
518 fulfillment_time => undef,
521 { order_by => { ahr => "request_time" } }
524 if ( ! $self->api_name =~ /id_list/ ) {
525 flesh_hold_transits($holds);
529 return [ map { $_->id } @$holds ];
533 __PACKAGE__->register_method(
534 method => "uncancel_hold",
535 api_name => "open-ils.circ.hold.uncancel"
539 my($self, $client, $auth, $hold_id) = @_;
540 my $e = new_editor(authtoken=>$auth, xact=>1);
541 return $e->die_event unless $e->checkauth;
543 my $hold = $e->retrieve_action_hold_request($hold_id)
544 or return $e->die_event;
545 return $e->die_event unless $e->allowed('CANCEL_HOLDS', $hold->request_lib);
547 if ($hold->fulfillment_time) {
551 unless ($hold->cancel_time) {
556 # if configured to reset the request time, also reset the expire time
557 if($U->ou_ancestor_setting_value(
558 $hold->request_lib, 'circ.holds.uncancel.reset_request_time', $e)) {
560 $hold->request_time('now');
561 my $interval = $U->ou_ancestor_setting_value($hold->request_lib, OILS_SETTING_HOLD_EXPIRE);
563 my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
564 $hold->expire_time($U->epoch2ISO8601($date->epoch));
568 $hold->clear_cancel_time;
569 $hold->clear_cancel_cause;
570 $hold->clear_cancel_note;
571 $hold->clear_shelf_time;
572 $hold->clear_current_copy;
573 $hold->clear_capture_time;
574 $hold->clear_prev_check_time;
575 $hold->clear_shelf_expire_time;
577 $e->update_action_hold_request($hold) or return $e->die_event;
580 $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
586 __PACKAGE__->register_method(
587 method => "cancel_hold",
588 api_name => "open-ils.circ.hold.cancel",
590 desc => 'Cancels the specified hold. The login session is the requestor. If the requestor is different from the usr field ' .
591 'on the hold, the requestor must have CANCEL_HOLDS permissions. The hold may be either the hold object or the hold id',
593 {desc => 'Authentication token', type => 'string'},
594 {desc => 'Hold ID', type => 'number'},
595 {desc => 'Cause of Cancellation', type => 'string'},
596 {desc => 'Note', type => 'string'}
599 desc => '1 on success, event on error'
605 my($self, $client, $auth, $holdid, $cause, $note) = @_;
607 my $e = new_editor(authtoken=>$auth, xact=>1);
608 return $e->die_event unless $e->checkauth;
610 my $hold = $e->retrieve_action_hold_request($holdid)
611 or return $e->die_event;
613 if( $e->requestor->id ne $hold->usr ) {
614 return $e->die_event unless $e->allowed('CANCEL_HOLDS');
617 if ($hold->cancel_time) {
622 # If the hold is captured, reset the copy status
623 if( $hold->capture_time and $hold->current_copy ) {
625 my $copy = $e->retrieve_asset_copy($hold->current_copy)
626 or return $e->die_event;
628 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
629 $logger->info("canceling hold $holdid whose item is on the holds shelf");
630 # $logger->info("setting copy to status 'reshelving' on hold cancel");
631 # $copy->status(OILS_COPY_STATUS_RESHELVING);
632 # $copy->editor($e->requestor->id);
633 # $copy->edit_date('now');
634 # $e->update_asset_copy($copy) or return $e->event;
636 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
639 $logger->warn("! canceling hold [$hid] that is in transit");
640 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
643 my $trans = $e->retrieve_action_transit_copy($transid);
644 # Leave the transit alive, but set the copy status to
645 # reshelving so it will be properly reshelved when it gets back home
647 $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
648 $e->update_action_transit_copy($trans) or return $e->die_event;
654 $hold->cancel_time('now');
655 $hold->cancel_cause($cause);
656 $hold->cancel_note($note);
657 $e->update_action_hold_request($hold)
658 or return $e->die_event;
660 delete_hold_copy_maps($self, $e, $hold->id);
664 $U->create_events_for_hook('hold_request.cancel.staff', $hold, $hold->pickup_lib)
665 if $e->requestor->id != $hold->usr;
670 sub delete_hold_copy_maps {
675 my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
677 $editor->delete_action_hold_copy_map($_)
678 or return $editor->event;
684 my $update_hold_desc = 'The login session is the requestor. ' .
685 'If the requestor is different from the usr field on the hold, ' .
686 'the requestor must have UPDATE_HOLDS permissions. ' .
687 'If supplying a hash of hold data, "id" must be included. ' .
688 'The hash is ignored if a hold object is supplied, ' .
689 'so you should supply only one kind of hold data argument.' ;
691 __PACKAGE__->register_method(
692 method => "update_hold",
693 api_name => "open-ils.circ.hold.update",
695 desc => "Updates the specified hold. $update_hold_desc",
697 {desc => 'Authentication token', type => 'string'},
698 {desc => 'Hold Object', type => 'object'},
699 {desc => 'Hash of values to be applied', type => 'object'}
702 desc => 'Hold ID on success, event on error',
708 __PACKAGE__->register_method(
709 method => "batch_update_hold",
710 api_name => "open-ils.circ.hold.update.batch",
713 desc => "Updates the specified hold(s). $update_hold_desc",
715 {desc => 'Authentication token', type => 'string'},
716 {desc => 'Array of hold obejcts', type => 'array' },
717 {desc => 'Array of hashes of values to be applied', type => 'array' }
720 desc => 'Hold ID per success, event per error',
726 my($self, $client, $auth, $hold, $values) = @_;
727 my $e = new_editor(authtoken=>$auth, xact=>1);
728 return $e->die_event unless $e->checkauth;
729 my $resp = update_hold_impl($self, $e, $hold, $values);
730 if ($U->event_code($resp)) {
734 $e->commit; # FIXME: update_hold_impl already does $e->commit ??
738 sub batch_update_hold {
739 my($self, $client, $auth, $hold_list, $values_list) = @_;
740 my $e = new_editor(authtoken=>$auth);
741 return $e->die_event unless $e->checkauth;
743 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.
745 $values_list ||= []; # FIXME: either move this above $count declaration, or send an event if both lists undef. Probably the latter.
747 # FIXME: Failing over to [] guarantees warnings for "Use of unitialized value" in update_hold_impl call.
748 # FIXME: We should be sure we only call update_hold_impl with hold object OR hash, not both.
750 for my $idx (0..$count-1) {
752 my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
753 $e->xact_commit unless $U->event_code($resp);
754 $client->respond($resp);
758 return undef; # not in the register return type, assuming we should always have at least one list populated
761 sub update_hold_impl {
762 my($self, $e, $hold, $values) = @_;
765 $hold = $e->retrieve_action_hold_request($values->{id})
766 or return $e->die_event;
767 for my $k (keys %$values) {
768 if (defined $values->{$k}) {
769 $hold->$k($values->{$k});
771 my $f = "clear_$k"; $hold->$f();
776 my $orig_hold = $e->retrieve_action_hold_request($hold->id)
777 or return $e->die_event;
779 # don't allow the user to be changed
780 return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
782 if($hold->usr ne $e->requestor->id) {
783 # if the hold is for a different user, make sure the
784 # requestor has the appropriate permissions
785 my $usr = $e->retrieve_actor_user($hold->usr)
786 or return $e->die_event;
787 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
791 # --------------------------------------------------------------
792 # Changing the request time is like playing God
793 # --------------------------------------------------------------
794 if($hold->request_time ne $orig_hold->request_time) {
795 return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
796 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
799 # --------------------------------------------------------------
800 # if the hold is on the holds shelf or in transit and the pickup
801 # lib changes we need to create a new transit.
802 # --------------------------------------------------------------
803 if($orig_hold->pickup_lib ne $hold->pickup_lib) {
805 my $status = _hold_status($e, $hold);
807 if($status == 3) { # in transit
809 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
810 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
812 $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
814 # update the transit to reflect the new pickup location
815 my $transit = $e->search_action_hold_transit_copy(
816 {hold=>$hold->id, dest_recv_time => undef})->[0]
817 or return $e->die_event;
819 $transit->prev_dest($transit->dest); # mark the previous destination on the transit
820 $transit->dest($hold->pickup_lib);
821 $e->update_action_hold_transit_copy($transit) or return $e->die_event;
823 } elsif($status == 4) { # on holds shelf
825 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
826 return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
828 $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
830 # create the new transit
831 my $evt = transit_hold($e, $orig_hold, $hold, $e->retrieve_asset_copy($hold->current_copy));
836 update_hold_if_frozen($self, $e, $hold, $orig_hold);
837 $e->update_action_hold_request($hold) or return $e->die_event;
840 # a change to mint-condition changes the set of potential copies, so retarget the hold;
841 if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
842 _reset_hold($self, $e->requestor, $hold)
849 my($e, $orig_hold, $hold, $copy) = @_;
850 my $src = $orig_hold->pickup_lib;
851 my $dest = $hold->pickup_lib;
853 $logger->info("putting hold into transit on pickup_lib update");
855 my $transit = Fieldmapper::action::hold_transit_copy->new;
856 $transit->hold($hold->id);
857 $transit->source($src);
858 $transit->dest($dest);
859 $transit->target_copy($copy->id);
860 $transit->source_send_time('now');
861 $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
863 $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
864 $copy->editor($e->requestor->id);
865 $copy->edit_date('now');
867 $e->create_action_hold_transit_copy($transit) or return $e->die_event;
868 $e->update_asset_copy($copy) or return $e->die_event;
872 # if the hold is frozen, this method ensures that the hold is not "targeted",
873 # that is, it clears the current_copy and prev_check_time to essentiallly
874 # reset the hold. If it is being activated, it runs the targeter in the background
875 sub update_hold_if_frozen {
876 my($self, $e, $hold, $orig_hold) = @_;
877 return if $hold->capture_time;
879 if($U->is_true($hold->frozen)) {
880 $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
881 $hold->clear_current_copy;
882 $hold->clear_prev_check_time;
885 if($U->is_true($orig_hold->frozen)) {
886 $logger->info("Running targeter on activated hold ".$hold->id);
887 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
892 __PACKAGE__->register_method(
893 method => "hold_note_CUD",
894 api_name => "open-ils.circ.hold_request.note.cud",
896 desc => 'Create, update or delete a hold request note. If the operator (from Auth. token) '
897 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
899 { desc => 'Authentication token', type => 'string' },
900 { desc => 'Hold note object', type => 'object' }
903 desc => 'Returns the note ID, event on error'
909 my($self, $conn, $auth, $note) = @_;
911 my $e = new_editor(authtoken => $auth, xact => 1);
912 return $e->die_event unless $e->checkauth;
914 my $hold = $e->retrieve_action_hold_request($note->hold)
915 or return $e->die_event;
917 if($hold->usr ne $e->requestor->id) {
918 my $usr = $e->retrieve_actor_user($hold->usr);
919 return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
920 $note->staff('t') if $note->isnew;
924 $e->create_action_hold_request_note($note) or return $e->die_event;
925 } elsif($note->ischanged) {
926 $e->update_action_hold_request_note($note) or return $e->die_event;
927 } elsif($note->isdeleted) {
928 $e->delete_action_hold_request_note($note) or return $e->die_event;
936 __PACKAGE__->register_method(
937 method => "retrieve_hold_status",
938 api_name => "open-ils.circ.hold.status.retrieve",
940 desc => 'Calculates the current status of the hold. The requestor must have ' .
941 'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
943 { desc => 'Hold ID', type => 'number' }
946 # type => 'number', # event sometimes
947 desc => <<'END_OF_DESC'
948 Returns event on error or:
949 -1 on error (for now),
950 1 for 'waiting for copy to become available',
951 2 for 'waiting for copy capture',
954 5 for 'hold-shelf-delay'
961 sub retrieve_hold_status {
962 my($self, $client, $auth, $hold_id) = @_;
964 my $e = new_editor(authtoken => $auth);
965 return $e->event unless $e->checkauth;
966 my $hold = $e->retrieve_action_hold_request($hold_id)
969 if( $e->requestor->id != $hold->usr ) {
970 return $e->event unless $e->allowed('VIEW_HOLD');
973 return _hold_status($e, $hold);
979 if ($hold->cancel_time) {
982 return 1 unless $hold->current_copy;
983 return 2 unless $hold->capture_time;
985 my $copy = $hold->current_copy;
986 unless( ref $copy ) {
987 $copy = $e->retrieve_asset_copy($hold->current_copy)
991 return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
993 if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
995 my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
996 return 4 unless $hs_wait_interval;
998 # if a hold_shelf_status_delay interval is defined and start_time plus
999 # the interval is greater than now, consider the hold to be in the virtual
1000 # "on its way to the holds shelf" status. Return 5.
1002 my $transit = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
1003 my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
1004 $start_time = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
1005 my $end_time = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
1007 return 5 if $end_time > DateTime->now;
1016 __PACKAGE__->register_method(
1017 method => "retrieve_hold_queue_stats",
1018 api_name => "open-ils.circ.hold.queue_stats.retrieve",
1020 desc => 'Returns summary data about the state of a hold',
1022 { desc => 'Authentication token', type => 'string'},
1023 { desc => 'Hold ID', type => 'number'},
1026 desc => q/Summary object with keys:
1027 total_holds : total holds in queue
1028 queue_position : current queue position
1029 potential_copies : number of potential copies for this hold
1030 estimated_wait : estimated wait time in days
1031 status : hold status
1032 -1 => error or unexpected state,
1033 1 => 'waiting for copy to become available',
1034 2 => 'waiting for copy capture',
1037 5 => 'hold-shelf-delay'
1044 sub retrieve_hold_queue_stats {
1045 my($self, $conn, $auth, $hold_id) = @_;
1046 my $e = new_editor(authtoken => $auth);
1047 return $e->event unless $e->checkauth;
1048 my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1049 if($e->requestor->id != $hold->usr) {
1050 return $e->event unless $e->allowed('VIEW_HOLD');
1052 return retrieve_hold_queue_status_impl($e, $hold);
1055 sub retrieve_hold_queue_status_impl {
1059 # The holds queue is defined as the distinct set of holds that share at
1060 # least one potential copy with the context hold, plus any holds that
1061 # share the same hold type and target. The latter part exists to
1062 # accomodate holds that currently have no potential copies
1063 my $q_holds = $e->json_query({
1065 # fetch cut_in_line and request_time since they're in the order_by
1066 # and we're asking for distinct values
1067 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1068 from => { ahr => 'ahcm' },
1072 "field" => "cut_in_line",
1073 "transform" => "coalesce",
1075 "direction" => "desc"
1077 { "class" => "ahr", "field" => "request_time" }
1084 select => {ahcm => ['target_copy']},
1086 where => {hold => $hold->id}
1093 if (!@$q_holds) { # none? maybe we don't have a map ...
1094 $q_holds = $e->json_query({
1095 select => {ahr => ['id', 'cut_in_line', 'request_time']},
1100 "field" => "cut_in_line",
1101 "transform" => "coalesce",
1103 "direction" => "desc"
1105 { "class" => "ahr", "field" => "request_time" }
1108 hold_type => $hold->hold_type,
1109 target => $hold->target
1116 for my $h (@$q_holds) {
1117 last if $h->{id} == $hold->id;
1121 my $hold_data = $e->json_query({
1123 acp => [ {column => 'id', transform => 'count', aggregate => 1, alias => 'count'} ],
1124 ccm => [ {column =>'avg_wait_time'} ]
1130 ccm => {type => 'left'}
1135 where => {'+ahcm' => {hold => $hold->id} }
1138 my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1140 my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1141 my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1142 $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1143 $default_wait ||= '0 seconds';
1145 # Estimated wait time is the average wait time across the set
1146 # of potential copies, divided by the number of potential copies
1147 # times the queue position.
1149 my $combined_secs = 0;
1150 my $num_potentials = 0;
1152 for my $wait_data (@$hold_data) {
1153 my $count += $wait_data->{count};
1154 $combined_secs += $count *
1155 OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1156 $num_potentials += $count;
1159 my $estimated_wait = -1;
1161 if($num_potentials) {
1162 my $avg_wait = $combined_secs / $num_potentials;
1163 $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1164 $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1168 total_holds => scalar(@$q_holds),
1169 queue_position => $qpos,
1170 potential_copies => $num_potentials,
1171 status => _hold_status( $e, $hold ),
1172 estimated_wait => int($estimated_wait)
1177 sub fetch_open_hold_by_current_copy {
1180 my $hold = $apputils->simplereq(
1182 'open-ils.cstore.direct.action.hold_request.search.atomic',
1183 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1184 return $hold->[0] if ref($hold);
1188 sub fetch_related_holds {
1191 return $apputils->simplereq(
1193 'open-ils.cstore.direct.action.hold_request.search.atomic',
1194 { current_copy => $copyid , cancel_time => undef, fulfillment_time => undef });
1198 __PACKAGE__->register_method(
1199 method => "hold_pull_list",
1200 api_name => "open-ils.circ.hold_pull_list.retrieve",
1202 desc => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1203 'The location is determined by the login session.',
1205 { desc => 'Limit (optional)', type => 'number'},
1206 { desc => 'Offset (optional)', type => 'number'},
1209 desc => 'reference to a list of holds, or event on failure',
1214 __PACKAGE__->register_method(
1215 method => "hold_pull_list",
1216 api_name => "open-ils.circ.hold_pull_list.id_list.retrieve",
1218 desc => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1219 'The location is determined by the login session.',
1221 { desc => 'Limit (optional)', type => 'number'},
1222 { desc => 'Offset (optional)', type => 'number'},
1225 desc => 'reference to a list of holds, or event on failure',
1230 __PACKAGE__->register_method(
1231 method => "hold_pull_list",
1232 api_name => "open-ils.circ.hold_pull_list.retrieve.count",
1234 desc => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1235 'The location is determined by the login session.',
1237 { desc => 'Limit (optional)', type => 'number'},
1238 { desc => 'Offset (optional)', type => 'number'},
1241 desc => 'Holds count (integer), or event on failure',
1248 sub hold_pull_list {
1249 my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1250 my( $reqr, $evt ) = $U->checkses($authtoken);
1251 return $evt if $evt;
1253 my $org = $reqr->ws_ou || $reqr->home_ou;
1254 # the perm locaiton shouldn't really matter here since holds
1255 # will exist all over and VIEW_HOLDS should be universal
1256 $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1257 return $evt if $evt;
1259 if($self->api_name =~ /count/) {
1261 my $count = $U->storagereq(
1262 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1263 $org, $limit, $offset );
1265 $logger->info("Grabbing pull list for org unit $org with $count items");
1268 } elsif( $self->api_name =~ /id_list/ ) {
1269 return $U->storagereq(
1270 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1271 $org, $limit, $offset );
1274 return $U->storagereq(
1275 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1276 $org, $limit, $offset );
1280 __PACKAGE__->register_method(
1281 method => "print_hold_pull_list",
1282 api_name => "open-ils.circ.hold_pull_list.print",
1284 desc => 'Returns an HTML-formatted holds pull list',
1286 { desc => 'Authtoken', type => 'string'},
1287 { desc => 'Org unit ID. Optional, defaults to workstation org unit', type => 'number'},
1290 desc => 'HTML string',
1296 sub print_hold_pull_list {
1297 my($self, $client, $auth, $org_id) = @_;
1299 my $e = new_editor(authtoken=>$auth);
1300 return $e->event unless $e->checkauth;
1302 $org_id = (defined $org_id) ? $org_id : $e->requestor->ws_ou;
1303 return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1305 my $hold_ids = $U->storagereq(
1306 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1309 return undef unless @$hold_ids;
1311 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1313 # Holds will /NOT/ be in order after this ...
1314 my $holds = $e->search_action_hold_request({id => $hold_ids}, {substream => 1});
1315 $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1317 # ... so we must resort.
1318 my $hold_map = +{map { $_->id => $_ } @$holds};
1319 my $sorted_holds = [];
1320 push @$sorted_holds, $hold_map->{$_} foreach @$hold_ids;
1322 return $U->fire_object_event(
1323 undef, "ahr.format.pull_list", $sorted_holds,
1324 $org_id, undef, undef, $client
1329 __PACKAGE__->register_method(
1330 method => "print_hold_pull_list_stream",
1332 api_name => "open-ils.circ.hold_pull_list.print.stream",
1334 desc => 'Returns a stream of fleshed holds',
1336 { desc => 'Authtoken', type => 'string'},
1337 { desc => 'Hash of optional param: Org unit ID (defaults to workstation org unit), limit, offset, sort (array of: acplo.position, call_number, request_time)',
1342 desc => 'A stream of fleshed holds',
1348 sub print_hold_pull_list_stream {
1349 my($self, $client, $auth, $params) = @_;
1351 my $e = new_editor(authtoken=>$auth);
1352 return $e->die_event unless $e->checkauth;
1354 delete($$params{org_id}) unless (int($$params{org_id}));
1355 delete($$params{limit}) unless (int($$params{limit}));
1356 delete($$params{offset}) unless (int($$params{offset}));
1357 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1358 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1359 $$params{chunk_size} ||= 10;
1361 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1362 return $e->die_event unless $e->allowed('VIEW_HOLD', $$params{org_id });
1365 if ($$params{sort} && @{ $$params{sort} }) {
1366 for my $s (@{ $$params{sort} }) {
1367 if ($s eq 'acplo.position') {
1369 "class" => "acplo", "field" => "position",
1370 "transform" => "coalesce", "params" => [999]
1372 } elsif ($s eq 'call_number') {
1373 push @$sort, {"class" => "acn", "field" => "label"};
1374 } elsif ($s eq 'request_time') {
1375 push @$sort, {"class" => "ahr", "field" => "request_time"};
1379 push @$sort, {"class" => "ahr", "field" => "request_time"};
1382 my $holds_ids = $e->json_query(
1384 "select" => {"ahr" => ["id"]},
1389 "fkey" => "current_copy",
1391 "circ_lib" => $$params{org_id}, "status" => [0,7]
1396 "fkey" => "call_number"
1400 "fkey" => "circ_lib",
1403 "location" => {"=" => {"+acp" => "location"}}
1412 "capture_time" => undef,
1413 "cancel_time" => undef,
1415 {"expire_time" => undef },
1416 {"expire_time" => {">" => "now"}}
1420 (@$sort ? (order_by => $sort) : ()),
1421 ($$params{limit} ? (limit => $$params{limit}) : ()),
1422 ($$params{offset} ? (offset => $$params{offset}) : ())
1423 }, {"substream" => 1}
1424 ) or return $e->die_event;
1426 $logger->info("about to stream back " . scalar(@$holds_ids) . " holds");
1429 for my $hid (@$holds_ids) {
1430 push @chunk, $e->retrieve_action_hold_request([
1434 "ahr" => ["usr", "current_copy"],
1436 "acp" => ["location", "call_number"],
1442 if (@chunk >= $$params{chunk_size}) {
1443 $client->respond( \@chunk );
1447 $client->respond_complete( \@chunk ) if (@chunk);
1454 __PACKAGE__->register_method(
1455 method => 'fetch_hold_notify',
1456 api_name => 'open-ils.circ.hold_notification.retrieve_by_hold',
1459 Returns a list of hold notification objects based on hold id.
1460 @param authtoken The loggin session key
1461 @param holdid The id of the hold whose notifications we want to retrieve
1462 @return An array of hold notification objects, event on error.
1466 sub fetch_hold_notify {
1467 my( $self, $conn, $authtoken, $holdid ) = @_;
1468 my( $requestor, $evt ) = $U->checkses($authtoken);
1469 return $evt if $evt;
1470 my ($hold, $patron);
1471 ($hold, $evt) = $U->fetch_hold($holdid);
1472 return $evt if $evt;
1473 ($patron, $evt) = $U->fetch_user($hold->usr);
1474 return $evt if $evt;
1476 $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1477 return $evt if $evt;
1479 $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1480 return $U->cstorereq(
1481 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1485 __PACKAGE__->register_method(
1486 method => 'create_hold_notify',
1487 api_name => 'open-ils.circ.hold_notification.create',
1489 Creates a new hold notification object
1490 @param authtoken The login session key
1491 @param notification The hold notification object to create
1492 @return ID of the new object on success, Event on error
1496 sub create_hold_notify {
1497 my( $self, $conn, $auth, $note ) = @_;
1498 my $e = new_editor(authtoken=>$auth, xact=>1);
1499 return $e->die_event unless $e->checkauth;
1501 my $hold = $e->retrieve_action_hold_request($note->hold)
1502 or return $e->die_event;
1503 my $patron = $e->retrieve_actor_user($hold->usr)
1504 or return $e->die_event;
1506 return $e->die_event unless
1507 $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1509 $note->notify_staff($e->requestor->id);
1510 $e->create_action_hold_notification($note) or return $e->die_event;
1515 __PACKAGE__->register_method(
1516 method => 'create_hold_note',
1517 api_name => 'open-ils.circ.hold_note.create',
1519 Creates a new hold request note object
1520 @param authtoken The login session key
1521 @param note The hold note object to create
1522 @return ID of the new object on success, Event on error
1526 sub create_hold_note {
1527 my( $self, $conn, $auth, $note ) = @_;
1528 my $e = new_editor(authtoken=>$auth, xact=>1);
1529 return $e->die_event unless $e->checkauth;
1531 my $hold = $e->retrieve_action_hold_request($note->hold)
1532 or return $e->die_event;
1533 my $patron = $e->retrieve_actor_user($hold->usr)
1534 or return $e->die_event;
1536 return $e->die_event unless
1537 $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn. Probably want something more specific
1539 $e->create_action_hold_request_note($note) or return $e->die_event;
1544 __PACKAGE__->register_method(
1545 method => 'reset_hold',
1546 api_name => 'open-ils.circ.hold.reset',
1548 Un-captures and un-targets a hold, essentially returning
1549 it to the state it was in directly after it was placed,
1550 then attempts to re-target the hold
1551 @param authtoken The login session key
1552 @param holdid The id of the hold
1558 my( $self, $conn, $auth, $holdid ) = @_;
1560 my ($hold, $evt) = $U->fetch_hold($holdid);
1561 return $evt if $evt;
1562 ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1563 return $evt if $evt;
1564 $evt = _reset_hold($self, $reqr, $hold);
1565 return $evt if $evt;
1570 __PACKAGE__->register_method(
1571 method => 'reset_hold_batch',
1572 api_name => 'open-ils.circ.hold.reset.batch'
1575 sub reset_hold_batch {
1576 my($self, $conn, $auth, $hold_ids) = @_;
1578 my $e = new_editor(authtoken => $auth);
1579 return $e->event unless $e->checkauth;
1581 for my $hold_id ($hold_ids) {
1583 my $hold = $e->retrieve_action_hold_request(
1584 [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}])
1585 or return $e->event;
1587 next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1588 _reset_hold($self, $e->requestor, $hold);
1596 my ($self, $reqr, $hold) = @_;
1598 my $e = new_editor(xact =>1, requestor => $reqr);
1600 $logger->info("reseting hold ".$hold->id);
1602 my $hid = $hold->id;
1604 if( $hold->capture_time and $hold->current_copy ) {
1606 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1607 or return $e->die_event;
1609 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1610 $logger->info("setting copy to status 'reshelving' on hold retarget");
1611 $copy->status(OILS_COPY_STATUS_RESHELVING);
1612 $copy->editor($e->requestor->id);
1613 $copy->edit_date('now');
1614 $e->update_asset_copy($copy) or return $e->die_event;
1616 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1618 # We don't want the copy to remain "in transit"
1619 $copy->status(OILS_COPY_STATUS_RESHELVING);
1620 $logger->warn("! reseting hold [$hid] that is in transit");
1621 my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1624 my $trans = $e->retrieve_action_transit_copy($transid);
1626 $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1627 my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1);
1628 $logger->info("Transit abort completed with result $evt");
1629 unless ("$evt" eq 1) {
1638 $hold->clear_capture_time;
1639 $hold->clear_current_copy;
1640 $hold->clear_shelf_time;
1641 $hold->clear_shelf_expire_time;
1643 $e->update_action_hold_request($hold) or return $e->die_event;
1647 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1653 __PACKAGE__->register_method(
1654 method => 'fetch_open_title_holds',
1655 api_name => 'open-ils.circ.open_holds.retrieve',
1657 Returns a list ids of un-fulfilled holds for a given title id
1658 @param authtoken The login session key
1659 @param id the id of the item whose holds we want to retrieve
1660 @param type The hold type - M, T, I, V, C, F, R
1664 sub fetch_open_title_holds {
1665 my( $self, $conn, $auth, $id, $type, $org ) = @_;
1666 my $e = new_editor( authtoken => $auth );
1667 return $e->event unless $e->checkauth;
1670 $org ||= $e->requestor->ws_ou;
1672 # return $e->search_action_hold_request(
1673 # { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1675 # XXX make me return IDs in the future ^--
1676 my $holds = $e->search_action_hold_request(
1679 cancel_time => undef,
1681 fulfillment_time => undef
1685 flesh_hold_transits($holds);
1690 sub flesh_hold_transits {
1692 for my $hold ( @$holds ) {
1694 $apputils->simplereq(
1696 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1697 { hold => $hold->id },
1698 { order_by => { ahtc => 'id desc' }, limit => 1 }
1704 sub flesh_hold_notices {
1705 my( $holds, $e ) = @_;
1706 $e ||= new_editor();
1708 for my $hold (@$holds) {
1709 my $notices = $e->search_action_hold_notification(
1711 { hold => $hold->id },
1712 { order_by => { anh => 'notify_time desc' } },
1717 $hold->notify_count(scalar(@$notices));
1719 my $n = $e->retrieve_action_hold_notification($$notices[0])
1720 or return $e->event;
1721 $hold->notify_time($n->notify_time);
1727 __PACKAGE__->register_method(
1728 method => 'fetch_captured_holds',
1729 api_name => 'open-ils.circ.captured_holds.on_shelf.retrieve',
1732 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
1733 @param authtoken The login session key
1734 @param org The org id of the location in question
1738 __PACKAGE__->register_method(
1739 method => 'fetch_captured_holds',
1740 api_name => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
1743 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
1744 @param authtoken The login session key
1745 @param org The org id of the location in question
1749 __PACKAGE__->register_method(
1750 method => 'fetch_captured_holds',
1751 api_name => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
1754 Returns list ids of shelf-expired un-fulfilled holds for a given title id
1755 @param authtoken The login session key
1756 @param org The org id of the location in question
1761 sub fetch_captured_holds {
1762 my( $self, $conn, $auth, $org ) = @_;
1764 my $e = new_editor(authtoken => $auth);
1765 return $e->die_event unless $e->checkauth;
1766 return $e->die_event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
1768 $org ||= $e->requestor->ws_ou;
1771 select => { ahr => ['id'] },
1776 fkey => 'current_copy'
1781 '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
1783 capture_time => { "!=" => undef },
1784 current_copy => { "!=" => undef },
1785 fulfillment_time => undef,
1787 cancel_time => undef,
1791 if($self->api_name =~ /expired/) {
1792 $query->{'where'}->{'+ahr'}->{'shelf_expire_time'} = {'<' => 'now'};
1793 $query->{'where'}->{'+ahr'}->{'shelf_time'} = {'!=' => undef};
1795 my $hold_ids = $e->json_query( $query );
1797 for my $hold_id (@$hold_ids) {
1798 if($self->api_name =~ /id_list/) {
1799 $conn->respond($hold_id->{id});
1803 $e->retrieve_action_hold_request([
1807 flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
1808 order_by => {anh => 'notify_time desc'}
1818 __PACKAGE__->register_method(
1819 method => "print_expired_holds_stream",
1820 api_name => "open-ils.circ.captured_holds.expired.print.stream",
1824 sub print_expired_holds_stream {
1825 my ($self, $client, $auth, $params) = @_;
1827 # No need to check specific permissions: we're going to call another method
1828 # that will do that.
1829 my $e = new_editor("authtoken" => $auth);
1830 return $e->die_event unless $e->checkauth;
1832 delete($$params{org_id}) unless (int($$params{org_id}));
1833 delete($$params{limit}) unless (int($$params{limit}));
1834 delete($$params{offset}) unless (int($$params{offset}));
1835 delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1836 delete($$params{chunk_size}) if ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1837 $$params{chunk_size} ||= 10;
1839 $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1841 my @hold_ids = $self->method_lookup(
1842 "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
1843 )->run($auth, $params->{"org_id"});
1848 } elsif (defined $U->event_code($hold_ids[0])) {
1850 return $hold_ids[0];
1853 $logger->info("about to stream back up to " . scalar(@hold_ids) . " expired holds");
1856 my @hid_chunk = splice @hold_ids, 0, $params->{"chunk_size"};
1858 my $result_chunk = $e->json_query({
1860 "acp" => ["barcode"],
1862 first_given_name second_given_name family_name alias
1871 "field" => "id", "fkey" => "current_copy",
1874 "field" => "id", "fkey" => "call_number",
1877 "field" => "id", "fkey" => "record"
1881 "acpl" => {"field" => "id", "fkey" => "location"}
1884 "au" => {"field" => "id", "fkey" => "usr"}
1887 "where" => {"+ahr" => {"id" => \@hid_chunk}}
1888 }) or return $e->die_event;
1889 $client->respond($result_chunk);
1896 __PACKAGE__->register_method(
1897 method => "check_title_hold_batch",
1898 api_name => "open-ils.circ.title_hold.is_possible.batch",
1901 desc => '@see open-ils.circ.title_hold.is_possible.batch',
1903 { desc => 'Authentication token', type => 'string'},
1904 { desc => 'Array of Hash of named parameters', type => 'array'},
1907 desc => 'Array of response objects',
1913 sub check_title_hold_batch {
1914 my($self, $client, $authtoken, $param_list) = @_;
1915 foreach (@$param_list) {
1916 my ($res) = $self->method_lookup('open-ils.circ.title_hold.is_possible')->run($authtoken, $_);
1917 $client->respond($res);
1923 __PACKAGE__->register_method(
1924 method => "check_title_hold",
1925 api_name => "open-ils.circ.title_hold.is_possible",
1927 desc => 'Determines if a hold were to be placed by a given user, ' .
1928 'whether or not said hold would have any potential copies to fulfill it.' .
1929 'The named paramaters of the second argument include: ' .
1930 'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
1931 'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' ,
1933 { desc => 'Authentication token', type => 'string'},
1934 { desc => 'Hash of named parameters', type => 'object'},
1937 desc => 'List of new message IDs (empty if none)',
1943 =head3 check_title_hold (token, hash)
1945 The named fields in the hash are:
1947 patronid - ID of the hold recipient (required)
1948 depth - hold range depth (default 0)
1949 pickup_lib - destination for hold, fallback value for selection_ou
1950 selection_ou - ID of org_unit establishing hard and soft hold boundary settings
1951 issuanceid - ID of the issuance to be held, required for Issuance level hold
1952 partid - ID of the monograph part to be held, required for monograph part level hold
1953 titleid - ID (BRN) of the title to be held, required for Title level hold
1954 volume_id - required for Volume level hold
1955 copy_id - required for Copy level hold
1956 mrid - required for Meta-record level hold
1957 hold_type - T, C (or R or F), I, V or M for Title, Copy, Issuance, Volume or Meta-record (default "T")
1959 All key/value pairs are passed on to do_possibility_checks.
1963 # FIXME: better params checking. what other params are required, if any?
1964 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
1965 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still
1966 # used in conditionals, where it may be undefined, causing a warning.
1967 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
1969 sub check_title_hold {
1970 my( $self, $client, $authtoken, $params ) = @_;
1971 my $e = new_editor(authtoken=>$authtoken);
1972 return $e->event unless $e->checkauth;
1974 my %params = %$params;
1975 my $depth = $params{depth} || 0;
1976 my $selection_ou = $params{selection_ou} || $params{pickup_lib};
1978 my $patron = $e->retrieve_actor_user($params{patronid})
1979 or return $e->event;
1981 if( $e->requestor->id ne $patron->id ) {
1982 return $e->event unless
1983 $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
1986 return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
1988 my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
1989 or return $e->event;
1991 my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
1992 my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
1995 my $return_depth = $hard_boundary; # default depth to return on success
1996 if(defined $soft_boundary and $depth < $soft_boundary) {
1997 # work up the tree and as soon as we find a potential copy, use that depth
1998 # also, make sure we don't go past the hard boundary if it exists
2000 # our min boundary is the greater of user-specified boundary or hard boundary
2001 my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?
2002 $hard_boundary : $depth;
2004 my $depth = $soft_boundary;
2005 while($depth >= $min_depth) {
2006 $logger->info("performing hold possibility check with soft boundary $depth");
2007 @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
2009 $return_depth = $depth;
2014 } elsif(defined $hard_boundary and $depth < $hard_boundary) {
2015 # there is no soft boundary, enforce the hard boundary if it exists
2016 $logger->info("performing hold possibility check with hard boundary $hard_boundary");
2017 @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
2019 # no boundaries defined, fall back to user specifed boundary or no boundary
2020 $logger->info("performing hold possibility check with no boundary");
2021 @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
2027 "depth" => $return_depth,
2028 "local_avail" => $status[1]
2030 } elsif ($status[2]) {
2031 my $n = scalar @{$status[2]};
2032 return {"success" => 0, "last_event" => $status[2]->[$n - 1]};
2034 return {"success" => 0};
2040 sub do_possibility_checks {
2041 my($e, $patron, $request_lib, $depth, %params) = @_;
2043 my $issuanceid = $params{issuanceid} || "";
2044 my $partid = $params{partid} || "";
2045 my $titleid = $params{titleid} || "";
2046 my $volid = $params{volume_id};
2047 my $copyid = $params{copy_id};
2048 my $mrid = $params{mrid} || "";
2049 my $pickup_lib = $params{pickup_lib};
2050 my $hold_type = $params{hold_type} || 'T';
2051 my $selection_ou = $params{selection_ou} || $pickup_lib;
2058 if( $hold_type eq OILS_HOLD_TYPE_FORCE || $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_COPY ) {
2060 return $e->event unless $copy = $e->retrieve_asset_copy($copyid);
2061 return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
2062 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2064 return verify_copy_for_hold(
2065 $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib
2068 } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2070 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
2071 return $e->event unless $title = $e->retrieve_biblio_record_entry($volume->record);
2073 return _check_volume_hold_is_possible(
2074 $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2077 } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
2079 return _check_title_hold_is_possible(
2080 $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2083 } elsif( $hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2085 return _check_issuance_hold_is_possible(
2086 $issuanceid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2089 } elsif( $hold_type eq OILS_HOLD_TYPE_MONOPART ) {
2091 return _check_monopart_hold_is_possible(
2092 $partid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2095 } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2097 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
2098 my @recs = map { $_->source } @$maps;
2100 for my $rec (@recs) {
2101 @status = _check_title_hold_is_possible(
2102 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2108 # else { Unrecognized hold_type ! } # FIXME: return error? or 0?
2112 sub create_ranged_org_filter {
2113 my($e, $selection_ou, $depth) = @_;
2115 # find the orgs from which this hold may be fulfilled,
2116 # based on the selection_ou and depth
2118 my $top_org = $e->search_actor_org_unit([
2119 {parent_ou => undef},
2120 {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
2123 return () if $depth == $top_org->ou_type->depth;
2125 my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
2126 %org_filter = (circ_lib => []);
2127 push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
2129 $logger->info("hold org filter at depth $depth and selection_ou ".
2130 "$selection_ou created list of @{$org_filter{circ_lib}}");
2136 sub _check_title_hold_is_possible {
2137 my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2139 my $e = new_editor();
2140 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2142 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2143 my $copies = $e->json_query(
2145 select => { acp => ['id', 'circ_lib'] },
2150 fkey => 'call_number',
2154 filter => { id => $titleid },
2159 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2160 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2164 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2169 $logger->info("title possible found ".scalar(@$copies)." potential copies");
2173 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2174 "payload" => {"fail_part" => "no_ultimate_items"}
2179 # -----------------------------------------------------------------------
2180 # sort the copies into buckets based on their circ_lib proximity to
2181 # the patron's home_ou.
2182 # -----------------------------------------------------------------------
2184 my $home_org = $patron->home_ou;
2185 my $req_org = $request_lib->id;
2187 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2189 $prox_cache{$home_org} =
2190 $e->search_actor_org_unit_proximity({from_org => $home_org})
2191 unless $prox_cache{$home_org};
2192 my $home_prox = $prox_cache{$home_org};
2195 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2196 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2198 my @keys = sort { $a <=> $b } keys %buckets;
2201 if( $home_org ne $req_org ) {
2202 # -----------------------------------------------------------------------
2203 # shove the copies close to the request_lib into the primary buckets
2204 # directly before the farthest away copies. That way, they are not
2205 # given priority, but they are checked before the farthest copies.
2206 # -----------------------------------------------------------------------
2207 $prox_cache{$req_org} =
2208 $e->search_actor_org_unit_proximity({from_org => $req_org})
2209 unless $prox_cache{$req_org};
2210 my $req_prox = $prox_cache{$req_org};
2213 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2214 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2216 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2217 my $new_key = $highest_key - 0.5; # right before the farthest prox
2218 my @keys2 = sort { $a <=> $b } keys %buckets2;
2219 for my $key (@keys2) {
2220 last if $key >= $highest_key;
2221 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2225 @keys = sort { $a <=> $b } keys %buckets;
2230 OUTER: for my $key (@keys) {
2231 my @cps = @{$buckets{$key}};
2233 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2235 for my $copyid (@cps) {
2237 next if $seen{$copyid};
2238 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2239 my $copy = $e->retrieve_asset_copy($copyid);
2240 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2242 unless($title) { # grab the title if we don't already have it
2243 my $vol = $e->retrieve_asset_call_number(
2244 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2245 $title = $vol->record;
2248 @status = verify_copy_for_hold(
2249 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2251 last OUTER if $status[0];
2258 sub _check_issuance_hold_is_possible {
2259 my( $issuanceid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2261 my $e = new_editor();
2262 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2264 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2265 my $copies = $e->json_query(
2267 select => { acp => ['id', 'circ_lib'] },
2273 filter => { issuance => $issuanceid }
2275 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2276 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2280 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2286 $logger->info("issuance possible found ".scalar(@$copies)." potential copies");
2290 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2291 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2296 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2297 "payload" => {"fail_part" => "no_ultimate_items"}
2305 # -----------------------------------------------------------------------
2306 # sort the copies into buckets based on their circ_lib proximity to
2307 # the patron's home_ou.
2308 # -----------------------------------------------------------------------
2310 my $home_org = $patron->home_ou;
2311 my $req_org = $request_lib->id;
2313 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2315 $prox_cache{$home_org} =
2316 $e->search_actor_org_unit_proximity({from_org => $home_org})
2317 unless $prox_cache{$home_org};
2318 my $home_prox = $prox_cache{$home_org};
2321 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2322 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2324 my @keys = sort { $a <=> $b } keys %buckets;
2327 if( $home_org ne $req_org ) {
2328 # -----------------------------------------------------------------------
2329 # shove the copies close to the request_lib into the primary buckets
2330 # directly before the farthest away copies. That way, they are not
2331 # given priority, but they are checked before the farthest copies.
2332 # -----------------------------------------------------------------------
2333 $prox_cache{$req_org} =
2334 $e->search_actor_org_unit_proximity({from_org => $req_org})
2335 unless $prox_cache{$req_org};
2336 my $req_prox = $prox_cache{$req_org};
2339 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2340 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2342 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2343 my $new_key = $highest_key - 0.5; # right before the farthest prox
2344 my @keys2 = sort { $a <=> $b } keys %buckets2;
2345 for my $key (@keys2) {
2346 last if $key >= $highest_key;
2347 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2351 @keys = sort { $a <=> $b } keys %buckets;
2356 OUTER: for my $key (@keys) {
2357 my @cps = @{$buckets{$key}};
2359 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2361 for my $copyid (@cps) {
2363 next if $seen{$copyid};
2364 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2365 my $copy = $e->retrieve_asset_copy($copyid);
2366 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2368 unless($title) { # grab the title if we don't already have it
2369 my $vol = $e->retrieve_asset_call_number(
2370 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2371 $title = $vol->record;
2374 @status = verify_copy_for_hold(
2375 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2377 last OUTER if $status[0];
2382 if (!defined($empty_ok)) {
2383 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2384 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2387 return (1,0) if ($empty_ok);
2392 sub _check_monopart_hold_is_possible {
2393 my( $partid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2395 my $e = new_editor();
2396 my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2398 # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2399 my $copies = $e->json_query(
2401 select => { acp => ['id', 'circ_lib'] },
2405 field => 'target_copy',
2407 filter => { part => $partid }
2409 acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2410 ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
2414 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2420 $logger->info("monopart possible found ".scalar(@$copies)." potential copies");
2424 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2425 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2430 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2431 "payload" => {"fail_part" => "no_ultimate_items"}
2439 # -----------------------------------------------------------------------
2440 # sort the copies into buckets based on their circ_lib proximity to
2441 # the patron's home_ou.
2442 # -----------------------------------------------------------------------
2444 my $home_org = $patron->home_ou;
2445 my $req_org = $request_lib->id;
2447 $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2449 $prox_cache{$home_org} =
2450 $e->search_actor_org_unit_proximity({from_org => $home_org})
2451 unless $prox_cache{$home_org};
2452 my $home_prox = $prox_cache{$home_org};
2455 my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2456 push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2458 my @keys = sort { $a <=> $b } keys %buckets;
2461 if( $home_org ne $req_org ) {
2462 # -----------------------------------------------------------------------
2463 # shove the copies close to the request_lib into the primary buckets
2464 # directly before the farthest away copies. That way, they are not
2465 # given priority, but they are checked before the farthest copies.
2466 # -----------------------------------------------------------------------
2467 $prox_cache{$req_org} =
2468 $e->search_actor_org_unit_proximity({from_org => $req_org})
2469 unless $prox_cache{$req_org};
2470 my $req_prox = $prox_cache{$req_org};
2473 my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2474 push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2476 my $highest_key = $keys[@keys - 1]; # the farthest prox in the exising buckets
2477 my $new_key = $highest_key - 0.5; # right before the farthest prox
2478 my @keys2 = sort { $a <=> $b } keys %buckets2;
2479 for my $key (@keys2) {
2480 last if $key >= $highest_key;
2481 push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2485 @keys = sort { $a <=> $b } keys %buckets;
2490 OUTER: for my $key (@keys) {
2491 my @cps = @{$buckets{$key}};
2493 $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2495 for my $copyid (@cps) {
2497 next if $seen{$copyid};
2498 $seen{$copyid} = 1; # there could be dupes given the merged buckets
2499 my $copy = $e->retrieve_asset_copy($copyid);
2500 $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2502 unless($title) { # grab the title if we don't already have it
2503 my $vol = $e->retrieve_asset_call_number(
2504 [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2505 $title = $vol->record;
2508 @status = verify_copy_for_hold(
2509 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2511 last OUTER if $status[0];
2516 if (!defined($empty_ok)) {
2517 $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2518 $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2521 return (1,0) if ($empty_ok);
2527 sub _check_volume_hold_is_possible {
2528 my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2529 my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
2530 my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
2531 $logger->info("checking possibility of volume hold for volume ".$vol->id);
2536 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2537 "payload" => {"fail_part" => "no_ultimate_items"}
2543 for my $copy ( @$copies ) {
2544 @status = verify_copy_for_hold(
2545 $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
2553 sub verify_copy_for_hold {
2554 my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib ) = @_;
2555 $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
2556 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2557 { patron => $patron,
2558 requestor => $requestor,
2561 title_descriptor => $title->fixed_fields, # this is fleshed into the title object
2562 pickup_lib => $pickup_lib,
2563 request_lib => $request_lib,
2565 show_event_list => 1
2570 (not scalar @$permitted), # true if permitted is an empty arrayref
2572 ($copy->circ_lib == $pickup_lib) and
2573 ($copy->status == OILS_COPY_STATUS_AVAILABLE)
2581 sub find_nearest_permitted_hold {
2584 my $editor = shift; # CStoreEditor object
2585 my $copy = shift; # copy to target
2586 my $user = shift; # staff
2587 my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
2589 my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
2591 my $bc = $copy->barcode;
2593 # find any existing holds that already target this copy
2594 my $old_holds = $editor->search_action_hold_request(
2595 { current_copy => $copy->id,
2596 cancel_time => undef,
2597 capture_time => undef
2601 # hold->type "R" means we need this copy
2602 for my $h (@$old_holds) { return ($h) if $h->hold_type eq 'R'; }
2605 my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
2607 $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
2608 " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
2610 my $fifo = $U->ou_ancestor_setting_value($user->ws_ou, 'circ.holds_fifo');
2612 # search for what should be the best holds for this copy to fulfill
2613 my $best_holds = $U->storagereq(
2614 "open-ils.storage.action.hold_request.nearest_hold.atomic",
2615 $user->ws_ou, $copy->id, 10, $hold_stall_interval, $fifo );
2617 unless(@$best_holds) {
2619 if( my $hold = $$old_holds[0] ) {
2620 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2624 $logger->info("circulator: no suitable holds found for copy $bc");
2625 return (undef, $evt);
2631 # for each potential hold, we have to run the permit script
2632 # to make sure the hold is actually permitted.
2635 for my $holdid (@$best_holds) {
2636 next unless $holdid;
2637 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
2639 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
2640 my $reqr = $reqr_cache{$hold->requestor} || $editor->retrieve_actor_user($hold->requestor);
2641 my $rlib = $org_cache{$hold->request_lib} || $editor->retrieve_actor_org_unit($hold->request_lib);
2643 $reqr_cache{$hold->requestor} = $reqr;
2644 $org_cache{$hold->request_lib} = $rlib;
2646 # see if this hold is permitted
2647 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2648 { patron_id => $hold->usr,
2651 pickup_lib => $hold->pickup_lib,
2652 request_lib => $rlib,
2664 unless( $best_hold ) { # no "good" permitted holds were found
2665 if( my $hold = $$old_holds[0] ) { # can we return a pre-targeted hold?
2666 $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2671 $logger->info("circulator: no suitable holds found for copy $bc");
2672 return (undef, $evt);
2675 $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
2677 # indicate a permitted hold was found
2678 return $best_hold if $check_only;
2680 # we've found a permitted hold. we need to "grab" the copy
2681 # to prevent re-targeted holds (next part) from re-grabbing the copy
2682 $best_hold->current_copy($copy->id);
2683 $editor->update_action_hold_request($best_hold)
2684 or return (undef, $editor->event);
2689 # re-target any other holds that already target this copy
2690 for my $old_hold (@$old_holds) {
2691 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
2692 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
2693 $old_hold->id." after a better hold [".$best_hold->id."] was found");
2694 $old_hold->clear_current_copy;
2695 $old_hold->clear_prev_check_time;
2696 $editor->update_action_hold_request($old_hold)
2697 or return (undef, $editor->event);
2698 push(@retarget, $old_hold->id);
2701 return ($best_hold, undef, (@retarget) ? \@retarget : undef);
2709 __PACKAGE__->register_method(
2710 method => 'all_rec_holds',
2711 api_name => 'open-ils.circ.holds.retrieve_all_from_title',
2715 my( $self, $conn, $auth, $title_id, $args ) = @_;
2717 my $e = new_editor(authtoken=>$auth);
2718 $e->checkauth or return $e->event;
2719 $e->allowed('VIEW_HOLD') or return $e->event;
2722 $args->{fulfillment_time} = undef; # we don't want to see old fulfilled holds
2723 $args->{cancel_time} = undef;
2725 my $resp = { volume_holds => [], copy_holds => [], metarecord_holds => [] };
2727 my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
2729 $resp->{metarecord_holds} = $e->search_action_hold_request(
2730 { hold_type => OILS_HOLD_TYPE_METARECORD,
2731 target => $mr_map->metarecord,
2737 $resp->{title_holds} = $e->search_action_hold_request(
2739 hold_type => OILS_HOLD_TYPE_TITLE,
2740 target => $title_id,
2744 my $vols = $e->search_asset_call_number(
2745 { record => $title_id, deleted => 'f' }, {idlist=>1});
2747 return $resp unless @$vols;
2749 $resp->{volume_holds} = $e->search_action_hold_request(
2751 hold_type => OILS_HOLD_TYPE_VOLUME,
2756 my $copies = $e->search_asset_copy(
2757 { call_number => $vols, deleted => 'f' }, {idlist=>1});
2759 return $resp unless @$copies;
2761 $resp->{copy_holds} = $e->search_action_hold_request(
2763 hold_type => OILS_HOLD_TYPE_COPY,
2775 __PACKAGE__->register_method(
2776 method => 'uber_hold',
2778 api_name => 'open-ils.circ.hold.details.retrieve'
2782 my($self, $client, $auth, $hold_id, $args) = @_;
2783 my $e = new_editor(authtoken=>$auth);
2784 $e->checkauth or return $e->event;
2785 return uber_hold_impl($e, $hold_id, $args);
2788 __PACKAGE__->register_method(
2789 method => 'batch_uber_hold',
2792 api_name => 'open-ils.circ.hold.details.batch.retrieve'
2795 sub batch_uber_hold {
2796 my($self, $client, $auth, $hold_ids, $args) = @_;
2797 my $e = new_editor(authtoken=>$auth);
2798 $e->checkauth or return $e->event;
2799 $client->respond(uber_hold_impl($e, $_, $args)) for @$hold_ids;
2803 sub uber_hold_impl {
2804 my($e, $hold_id, $args) = @_;
2807 my $hold = $e->retrieve_action_hold_request(
2812 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
2815 ) or return $e->event;
2817 if($hold->usr->id ne $e->requestor->id) {
2818 # A user is allowed to see his/her own holds
2819 $e->allowed('VIEW_HOLD') or return $e->event;
2820 $hold->notes( # filter out any non-staff ("private") notes
2821 [ grep { !$U->is_true($_->staff) } @{$hold->notes} ] );
2824 # caller is asking for own hold, but may not have permission to view staff notes
2825 unless($e->allowed('VIEW_HOLD')) {
2826 $hold->notes( # filter out any staff notes
2827 [ grep { $U->is_true($_->staff) } @{$hold->notes} ] );
2831 my $user = $hold->usr;
2832 $hold->usr($user->id);
2835 my( $mvr, $volume, $copy, $issuance, $part, $bre ) = find_hold_mvr($e, $hold, $args->{suppress_mvr});
2837 flesh_hold_notices([$hold], $e) unless $args->{suppress_notices};
2838 flesh_hold_transits([$hold]) unless $args->{suppress_transits};
2840 my $details = retrieve_hold_queue_status_impl($e, $hold);
2844 ($copy ? (copy => $copy) : ()),
2845 ($volume ? (volume => $volume) : ()),
2846 ($issuance ? (issuance => $issuance) : ()),
2847 ($part ? (part => $part) : ()),
2848 ($args->{include_bre} ? (bre => $bre) : ()),
2849 ($args->{suppress_mvr} ? () : (mvr => $mvr)),
2853 unless($args->{suppress_patron_details}) {
2854 my $card = $e->retrieve_actor_card($user->card) or return $e->event;
2855 $resp->{patron_first} = $user->first_given_name,
2856 $resp->{patron_last} = $user->family_name,
2857 $resp->{patron_barcode} = $card->barcode,
2858 $resp->{patron_alias} = $user->alias,
2866 # -----------------------------------------------------
2867 # Returns the MVR object that represents what the
2869 # -----------------------------------------------------
2871 my( $e, $hold, $no_mvr ) = @_;
2879 if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2880 my $mr = $e->retrieve_metabib_metarecord($hold->target)
2881 or return $e->event;
2882 $tid = $mr->master_record;
2884 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
2885 $tid = $hold->target;
2887 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2888 $volume = $e->retrieve_asset_call_number($hold->target)
2889 or return $e->event;
2890 $tid = $volume->record;
2892 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2893 $issuance = $e->retrieve_serial_issuance([
2895 {flesh => 1, flesh_fields => {siss => [ qw/subscription/ ]}}
2896 ]) or return $e->event;
2898 $tid = $issuance->subscription->record_entry;
2900 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_MONOPART ) {
2901 $part = $e->retrieve_biblio_monographic_part([
2903 {flesh => 1, flesh_fields => {bmp => [ qw/record/ ]}}
2904 ]) or return $e->event;
2906 $tid = $part->record;
2908 } elsif( $hold->hold_type eq OILS_HOLD_TYPE_COPY ) {
2909 $copy = $e->retrieve_asset_copy([
2911 {flesh => 1, flesh_fields => {acp => ['call_number']}}
2912 ]) or return $e->event;
2914 $volume = $copy->call_number;
2915 $tid = $volume->record;
2918 if(!$copy and ref $hold->current_copy ) {
2919 $copy = $hold->current_copy;
2920 $hold->current_copy($copy->id);
2923 if(!$volume and $copy) {
2924 $volume = $e->retrieve_asset_call_number($copy->call_number);
2927 # TODO return metarcord mvr for M holds
2928 my $title = $e->retrieve_biblio_record_entry($tid);
2929 return ( ($no_mvr) ? undef : $U->record_to_mvr($title), $volume, $copy, $issuance, $part, $title );
2932 __PACKAGE__->register_method(
2933 method => 'clear_shelf_cache',
2934 api_name => 'open-ils.circ.hold.clear_shelf.get_cache',
2938 Returns the holds processed with the given cache key
2943 sub clear_shelf_cache {
2944 my($self, $client, $auth, $cache_key, $chunk_size) = @_;
2945 my $e = new_editor(authtoken => $auth, xact => 1);
2946 return $e->die_event unless $e->checkauth and $e->allowed('VIEW_HOLD');
2949 my $hold_data = OpenSRF::Utils::Cache->new('global')->get_cache($cache_key);
2952 $logger->info("no hold data found in cache"); # XXX TODO return event
2958 foreach (keys %$hold_data) {
2959 $maximum += scalar(@{ $hold_data->{$_} });
2961 $client->respond({"maximum" => $maximum, "progress" => 0});
2963 for my $action (sort keys %$hold_data) {
2964 while (@{$hold_data->{$action}}) {
2965 my @hid_chunk = splice @{$hold_data->{$action}}, 0, $chunk_size;
2967 my $result_chunk = $e->json_query({
2969 "acp" => ["barcode"],
2971 first_given_name second_given_name family_name alias
2981 "field" => "id", "fkey" => "current_copy",
2984 "field" => "id", "fkey" => "call_number",
2987 "field" => "id", "fkey" => "record"
2991 "acpl" => {"field" => "id", "fkey" => "location"}
2994 "au" => {"field" => "id", "fkey" => "usr"}
2997 "where" => {"+ahr" => {"id" => \@hid_chunk}}
2998 }, {"substream" => 1}) or return $e->die_event;
3002 +{"action" => $action, "hold_details" => $_}
3013 __PACKAGE__->register_method(
3014 method => 'clear_shelf_process',
3016 api_name => 'open-ils.circ.hold.clear_shelf.process',
3019 1. Find all holds that have expired on the holds shelf
3021 3. If a clear-shelf status is configured, put targeted copies into this status
3022 4. Divide copies into 3 groups: items to transit, items to reshelve, and items
3023 that are needed for holds. No subsequent action is taken on the holds
3024 or items after grouping.
3029 sub clear_shelf_process {
3030 my($self, $client, $auth, $org_id) = @_;
3032 my $e = new_editor(authtoken=>$auth, xact => 1);
3033 $e->checkauth or return $e->die_event;
3034 my $cache = OpenSRF::Utils::Cache->new('global');
3036 $org_id ||= $e->requestor->ws_ou;
3037 $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
3039 my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
3041 # Find holds on the shelf that have been there too long
3042 my $hold_ids = $e->search_action_hold_request(
3043 { shelf_expire_time => {'<' => 'now'},
3044 pickup_lib => $org_id,
3045 cancel_time => undef,
3046 fulfillment_time => undef,
3047 shelf_time => {'!=' => undef},
3048 capture_time => {'!=' => undef},
3049 current_copy => {'!=' => undef},
3055 my $chunk_size = 25; # chunked status updates
3057 for my $hold_id (@$hold_ids) {
3059 $logger->info("Clear shelf processing hold $hold_id");
3061 my $hold = $e->retrieve_action_hold_request([
3064 flesh_fields => {ahr => ['current_copy']}
3068 $hold->cancel_time('now');
3069 $hold->cancel_cause(2); # Hold Shelf expiration
3070 $e->update_action_hold_request($hold) or return $e->die_event;
3071 delete_hold_copy_maps($self, $e, $hold->id) and return $e->die_event;
3073 my $copy = $hold->current_copy;
3075 if($copy_status or $copy_status == 0) {
3076 # if a clear-shelf copy status is defined, update the copy
3077 $copy->status($copy_status);
3078 $copy->edit_date('now');
3079 $copy->editor($e->requestor->id);
3080 $e->update_asset_copy($copy) or return $e->die_event;
3083 push(@holds, $hold);
3084 $client->respond({maximum => scalar(@holds), progress => $counter}) if ( (++$counter % $chunk_size) == 0);
3095 for my $hold (@holds) {
3097 my $copy = $hold->current_copy;
3098 my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
3102 push(@{$cache_data{hold}}, $hold->id); # copy is needed for a hold
3104 } elsif($copy->circ_lib != $e->requestor->ws_ou) {
3106 push(@{$cache_data{transit}}, $hold->id); # copy needs to transit
3110 push(@{$cache_data{shelf}}, $hold->id); # copy needs to go back to the shelf
3114 my $cache_key = md5_hex(time . $$ . rand());
3115 $logger->info("clear_shelf_cache: storing under $cache_key");
3116 $cache->put_cache($cache_key, \%cache_data, 7200); # TODO: 2 hours. configurable?
3118 # tell the client we're done
3119 $client->respond_complete({cache_key => $cache_key});
3121 # fire off the hold cancelation trigger and wait for response so don't flood the service
3122 $U->create_events_for_hook(
3123 'hold_request.cancel.expire_holds_shelf',
3124 $_, $org_id, undef, undef, 1) for @holds;
3127 # tell the client we're done
3128 $client->respond_complete;
3132 __PACKAGE__->register_method(
3133 method => 'usr_hold_summary',
3134 api_name => 'open-ils.circ.holds.user_summary',
3136 Returns a summary of holds statuses for a given user
3140 sub usr_hold_summary {
3141 my($self, $conn, $auth, $user_id) = @_;
3143 my $e = new_editor(authtoken=>$auth);
3144 $e->checkauth or return $e->event;
3145 $e->allowed('VIEW_HOLD') or return $e->event;
3147 my $holds = $e->search_action_hold_request(
3150 fulfillment_time => undef,
3151 cancel_time => undef,
3155 my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
3156 $summary{_hold_status($e, $_)} += 1 for @$holds;
3162 __PACKAGE__->register_method(
3163 method => 'hold_has_copy_at',
3164 api_name => 'open-ils.circ.hold.has_copy_at',
3167 'Returns the ID of the found copy and name of the shelving location if there is ' .
3168 'an available copy at the specified org unit. Returns empty hash otherwise. ' .
3169 'The anticipated use for this method is to determine whether an item is ' .
3170 'available at the library where the user is placing the hold (or, alternatively, '.
3171 'at the pickup library) to encourage bypassing the hold placement and just ' .
3172 'checking out the item.' ,
3174 { desc => 'Authentication Token', type => 'string' },
3175 { desc => 'Method Arguments. Options include: hold_type, hold_target, org_unit. '
3176 . 'hold_type is the hold type code (T, V, C, M, ...). '
3177 . 'hold_target is the identifier of the hold target object. '
3178 . 'org_unit is org unit ID.',
3183 desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
3189 sub hold_has_copy_at {
3190 my($self, $conn, $auth, $args) = @_;
3192 my $e = new_editor(authtoken=>$auth);
3193 $e->checkauth or return $e->event;
3195 my $hold_type = $$args{hold_type};
3196 my $hold_target = $$args{hold_target};
3197 my $org_unit = $$args{org_unit};
3200 select => {acp => ['id'], acpl => ['name']},
3203 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
3204 ccs => {field => 'id', filter => { holdable => 't'}, fkey => 'status' }
3207 where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit}},
3211 if($hold_type eq 'C') {
3213 $query->{where}->{'+acp'}->{id} = $hold_target;
3215 } elsif($hold_type eq 'V') {
3217 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3219 } elsif($hold_type eq 'T') {
3221 $query->{from}->{acp}->{acn} = {
3223 fkey => 'call_number',
3227 filter => {id => $hold_target},
3235 $query->{from}->{acp}->{acn} = {
3237 fkey => 'call_number',
3246 filter => {metarecord => $hold_target},
3254 my $res = $e->json_query($query)->[0] or return {};
3255 return {copy => $res->{id}, location => $res->{name}} if $res;
3259 # returns true if the user already has an item checked out
3260 # that could be used to fulfill the requested hold.
3261 sub hold_item_is_checked_out {
3262 my($e, $user_id, $hold_type, $hold_target) = @_;
3265 select => {acp => ['id']},
3266 from => {acp => {}},
3270 in => { # copies for circs the user has checked out
3271 select => {circ => ['target_copy']},
3275 checkin_time => undef,
3277 {stop_fines => ["MAXFINES","LONGOVERDUE"]},
3278 {stop_fines => undef}
3288 if($hold_type eq 'C' || $hold_type eq 'R' || $hold_type eq 'F') {
3290 $query->{where}->{'+acp'}->{id}->{in}->{where}->{'target_copy'} = $hold_target;
3292 } elsif($hold_type eq 'V') {
3294 $query->{where}->{'+acp'}->{call_number} = $hold_target;
3296 } elsif($hold_type eq 'P') {
3298 $query->{from}->{acp}->{acpm} = {
3299 field => 'target_copy',
3301 filter => {part => $hold_target},
3304 } elsif($hold_type eq 'I') {
3306 $query->{from}->{acp}->{sitem} = {
3309 filter => {issuance => $hold_target},
3312 } elsif($hold_type eq 'T') {
3314 $query->{from}->{acp}->{acn} = {
3316 fkey => 'call_number',
3320 filter => {id => $hold_target},
3328 $query->{from}->{acp}->{acn} = {
3330 fkey => 'call_number',
3339 filter => {metarecord => $hold_target},
3347 return $e->json_query($query)->[0];
3350 __PACKAGE__->register_method(
3351 method => 'change_hold_title',
3352 api_name => 'open-ils.circ.hold.change_title',
3355 Updates all title level holds targeting the specified bibs to point a new bib./,
3357 { desc => 'Authentication Token', type => 'string' },
3358 { desc => 'New Target Bib Id', type => 'number' },
3359 { desc => 'Old Target Bib Ids', type => 'array' },
3361 return => { desc => '1 on success' }
3365 sub change_hold_title {
3366 my( $self, $client, $auth, $new_bib_id, $bib_ids ) = @_;
3368 my $e = new_editor(authtoken=>$auth, xact=>1);
3369 return $e->die_event unless $e->checkauth;
3371 my $holds = $e->search_action_hold_request(
3374 cancel_time => undef,
3375 fulfillment_time => undef,
3381 flesh_fields => { ahr => ['usr'] }
3387 for my $hold (@$holds) {
3388 $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3389 $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3390 $hold->target( $new_bib_id );
3391 $e->update_action_hold_request($hold) or return $e->die_event;
3400 __PACKAGE__->register_method(
3401 method => 'rec_hold_count',
3402 api_name => 'open-ils.circ.bre.holds.count',
3404 desc => q/Returns the total number of holds that target the
3405 selected bib record or its associated copies and call_numbers/,
3407 { desc => 'Bib ID', type => 'number' },
3409 return => {desc => 'Hold count', type => 'number'}
3413 __PACKAGE__->register_method(
3414 method => 'rec_hold_count',
3415 api_name => 'open-ils.circ.mmr.holds.count',
3417 desc => q/Returns the total number of holds that target the
3418 selected metarecord or its associated copies, call_numbers, and bib records/,
3420 { desc => 'Metarecord ID', type => 'number' },
3422 return => {desc => 'Hold count', type => 'number'}
3426 # XXX Need to add type I (and, soon, type P) holds to these counts
3427 sub rec_hold_count {
3428 my($self, $conn, $target_id) = @_;
3435 filter => {metarecord => $target_id}
3442 filter => { id => $target_id },
3447 if($self->api_name =~ /mmr/) {
3448 delete $bre_join->{bre}->{filter};
3449 $bre_join->{bre}->{join} = $mmr_join;
3455 fkey => 'call_number',
3461 select => {ahr => [{column => 'id', transform => 'count', alias => 'count'}]},
3465 cancel_time => undef,
3466 fulfillment_time => undef,
3470 hold_type => [qw/C F R/],
3473 select => {acp => ['id']},
3474 from => { acp => $cn_join }
3484 select => {acn => ['id']},
3485 from => {acn => $bre_join}
3493 target => $target_id
3501 if($self->api_name =~ /mmr/) {
3502 $query->{where}->{'+ahr'}->{'-or'}->[2] = {
3507 select => {bre => ['id']},
3508 from => {bre => $mmr_join}
3514 $query->{where}->{'+ahr'}->{'-or'}->[3] = {
3517 target => $target_id
3523 return new_editor()->json_query($query)->[0]->{count};