]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ/Holds.pm
added support for setting hold expire time using an interval defined in the org unit...
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Circ / Holds.pm
1 # ---------------------------------------------------------------
2 # Copyright (C) 2005  Georgia Public Library Service 
3 # Bill Erickson <highfalutin@gmail.com>
4
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.
9
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 # ---------------------------------------------------------------
15
16
17 package OpenILS::Application::Circ::Holds;
18 use base qw/OpenILS::Application/;
19 use strict; use warnings;
20 use OpenILS::Application::AppUtils;
21 use DateTime;
22 use Data::Dumper;
23 use OpenSRF::EX qw(:try);
24 use OpenILS::Perm;
25 use OpenILS::Event;
26 use OpenSRF::Utils;
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
34 my $apputils = "OpenILS::Application::AppUtils";
35 my $U = $apputils;
36
37
38
39
40 __PACKAGE__->register_method(
41         method  => "create_hold",
42         api_name        => "open-ils.circ.holds.create",
43         notes           => <<NOTE);
44 Create a new hold for an item.  From a permissions perspective, 
45 the login session is used as the 'requestor' of the hold.  
46 The hold recipient is determined by the 'usr' setting within
47 the hold object.
48
49 First we verify the requestion has holds request permissions.
50 Then we verify that the recipient is allowed to make the given hold.
51 If not, we see if the requestor has "override" capabilities.  If not,
52 a permission exception is returned.  If permissions allow, we cycle
53 through the set of holds objects and create.
54
55 If the recipient does not have permission to place multiple holds
56 on a single title and said operation is attempted, a permission
57 exception is returned
58 NOTE
59
60
61 __PACKAGE__->register_method(
62         method  => "create_hold",
63         api_name        => "open-ils.circ.holds.create.override",
64         signature       => q/
65                 If the recipient is not allowed to receive the requested hold,
66                 call this method to attempt the override
67                 @see open-ils.circ.holds.create
68         /
69 );
70
71 sub create_hold {
72         my( $self, $conn, $auth, @holds ) = @_;
73         my $e = new_editor(authtoken=>$auth, xact=>1);
74         return $e->event unless $e->checkauth;
75
76         my $override = 1 if $self->api_name =~ /override/;
77
78         my $holds = (ref($holds[0] eq 'ARRAY')) ? $holds[0] : [@holds];
79
80 #       my @copyholds;
81
82         for my $hold (@$holds) {
83
84                 next unless $hold;
85                 my @events;
86
87                 my $requestor = $e->requestor;
88                 my $recipient = $requestor;
89
90
91                 if( $requestor->id ne $hold->usr ) {
92                         # Make sure the requestor is allowed to place holds for 
93                         # the recipient if they are not the same people
94                         $recipient = $e->retrieve_actor_user($hold->usr) or return $e->event;
95                         $e->allowed('REQUEST_HOLDS', $recipient->home_ou) or return $e->event;
96                 }
97
98                 # Now make sure the recipient is allowed to receive the specified hold
99                 my $pevt;
100                 my $porg                = $recipient->home_ou;
101                 my $rid         = $e->requestor->id;
102                 my $t                   = $hold->hold_type;
103
104                 # See if a duplicate hold already exists
105                 my $sargs = {
106                         usr                     => $recipient->id, 
107                         hold_type       => $t, 
108                         fulfillment_time => undef, 
109                         target          => $hold->target,
110                         cancel_time     => undef,
111                 };
112
113                 $sargs->{holdable_formats} = $hold->holdable_formats if $t eq 'M';
114                         
115                 my $existing = $e->search_action_hold_request($sargs); 
116                 push( @events, OpenILS::Event->new('HOLD_EXISTS')) if @$existing;
117
118                 if( $t eq OILS_HOLD_TYPE_METARECORD ) 
119                         { $pevt = $e->event unless $e->allowed('MR_HOLDS', $porg); }
120
121                 if( $t eq OILS_HOLD_TYPE_TITLE ) 
122                         { $pevt = $e->event unless $e->allowed('TITLE_HOLDS', $porg);  }
123
124                 if( $t eq OILS_HOLD_TYPE_VOLUME ) 
125                         { $pevt = $e->event unless $e->allowed('VOLUME_HOLDS', $porg); }
126
127                 if( $t eq OILS_HOLD_TYPE_COPY ) 
128                         { $pevt = $e->event unless $e->allowed('COPY_HOLDS', $porg); }
129
130                 return $pevt if $pevt;
131
132                 if( @events ) {
133                         if( $override ) {
134                                 for my $evt (@events) {
135                                         next unless $evt;
136                                         my $name = $evt->{textcode};
137                                         return $e->event unless $e->allowed("$name.override", $porg);
138                                 }
139                         } else {
140                                 return \@events;
141                         }
142                 }
143
144         # set the configured expire time
145         my $interval = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_HOLD_EXPIRE);
146         if($interval) {
147             my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
148             $hold->expire_time($U->epoch2ISO8601($date->epoch));
149         }
150
151                 $hold->requestor($e->requestor->id); 
152                 $hold->request_lib($e->requestor->ws_ou);
153                 $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
154                 $hold = $e->create_action_hold_request($hold) or return $e->event;
155         }
156
157         $e->commit;
158
159         $conn->respond_complete(1);
160
161     for(@holds) {
162         next if $U->is_true($_->frozen);
163             $U->storagereq(
164                     'open-ils.storage.action.hold_request.copy_targeter', 
165                     undef, $_->id );
166     }
167
168         return undef;
169 }
170
171 sub __create_hold {
172         my( $self, $client, $login_session, @holds) = @_;
173
174         if(!@holds){return 0;}
175         my( $user, $evt ) = $apputils->checkses($login_session);
176         return $evt if $evt;
177
178         my $holds;
179         if(ref($holds[0]) eq 'ARRAY') {
180                 $holds = $holds[0];
181         } else { $holds = [ @holds ]; }
182
183         $logger->debug("Iterating over holds requests...");
184
185         for my $hold (@$holds) {
186
187                 if(!$hold){next};
188                 my $type = $hold->hold_type;
189
190                 $logger->activity("User " . $user->id . 
191                         " creating new hold of type $type for user " . $hold->usr);
192
193                 my $recipient;
194                 if($user->id ne $hold->usr) {
195                         ( $recipient, $evt ) = $apputils->fetch_user($hold->usr);
196                         return $evt if $evt;
197
198                 } else {
199                         $recipient = $user;
200                 }
201
202
203                 my $perm = undef;
204
205                 # am I allowed to place holds for this user?
206                 if($hold->requestor ne $hold->usr) {
207                         $perm = _check_request_holds_perm($user->id, $user->home_ou);
208                         if($perm) { return $perm; }
209                 }
210
211                 # is this user allowed to have holds of this type?
212                 $perm = _check_holds_perm($type, $hold->requestor, $recipient->home_ou);
213         return $perm if $perm;
214
215                 #enforce the fact that the login is the one requesting the hold
216                 $hold->requestor($user->id); 
217                 $hold->selection_ou($recipient->home_ou) unless $hold->selection_ou;
218
219                 my $resp = $apputils->simplereq(
220                         'open-ils.storage',
221                         'open-ils.storage.direct.action.hold_request.create', $hold );
222
223                 if(!$resp) { 
224                         return OpenSRF::EX::ERROR ("Error creating hold"); 
225                 }
226         }
227
228         return 1;
229 }
230
231 # makes sure that a user has permission to place the type of requested hold
232 # returns the Perm exception if not allowed, returns undef if all is well
233 sub _check_holds_perm {
234         my($type, $user_id, $org_id) = @_;
235
236         my $evt;
237         if($type eq "M") {
238                 if($evt = $apputils->check_perms(
239                         $user_id, $org_id, "MR_HOLDS")) {
240                         return $evt;
241                 } 
242
243         } elsif ($type eq "T") {
244                 if($evt = $apputils->check_perms(
245                         $user_id, $org_id, "TITLE_HOLDS")) {
246                         return $evt;
247                 }
248
249         } elsif($type eq "V") {
250                 if($evt = $apputils->check_perms(
251                         $user_id, $org_id, "VOLUME_HOLDS")) {
252                         return $evt;
253                 }
254
255         } elsif($type eq "C") {
256                 if($evt = $apputils->check_perms(
257                         $user_id, $org_id, "COPY_HOLDS")) {
258                         return $evt;
259                 }
260         }
261
262         return undef;
263 }
264
265 # tests if the given user is allowed to place holds on another's behalf
266 sub _check_request_holds_perm {
267         my $user_id = shift;
268         my $org_id = shift;
269         if(my $evt = $apputils->check_perms(
270                 $user_id, $org_id, "REQUEST_HOLDS")) {
271                 return $evt;
272         }
273 }
274
275 __PACKAGE__->register_method(
276         method  => "retrieve_holds_by_id",
277         api_name        => "open-ils.circ.holds.retrieve_by_id",
278         notes           => <<NOTE);
279 Retrieve the hold, with hold transits attached, for the specified id The login session is the requestor and if the requestor is
280 different from the user, then the requestor must have VIEW_HOLD permissions.
281 NOTE
282
283
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;
289
290         my $holds = $e->search_action_hold_request(
291                 [
292                         { id =>  $hold_id , fulfillment_time => undef }, 
293                         { order_by => { ahr => "request_time" } }
294                 ]
295         );
296
297         flesh_hold_transits($holds);
298         flesh_hold_notices($holds, $e);
299         return $holds;
300 }
301
302
303 __PACKAGE__->register_method(
304         method  => "retrieve_holds",
305         api_name        => "open-ils.circ.holds.retrieve",
306         notes           => <<NOTE);
307 Retrieves all the holds, with hold transits attached, for the specified
308 user id.  The login session is the requestor and if the requestor is
309 different from the user, then the requestor must have VIEW_HOLD permissions.
310 NOTE
311
312 __PACKAGE__->register_method(
313         method  => "retrieve_holds",
314     authoritative => 1,
315         api_name        => "open-ils.circ.holds.id_list.retrieve",
316         notes           => <<NOTE);
317 Retrieves all the hold ids for the specified
318 user id.  The login session is the requestor and if the requestor is
319 different from the user, then the requestor must have VIEW_HOLD permissions.
320 NOTE
321
322 sub retrieve_holds {
323         my($self, $client, $login_session, $user_id) = @_;
324
325         my( $user, $target, $evt ) = $apputils->checkses_requestor(
326                 $login_session, $user_id, 'VIEW_HOLD' );
327         return $evt if $evt;
328
329         my $holds = $apputils->simplereq(
330                 'open-ils.cstore',
331                 "open-ils.cstore.direct.action.hold_request.search.atomic",
332                 { 
333                         usr =>  $user_id , 
334                         fulfillment_time => undef,
335                         cancel_time => undef,
336                 }, 
337                 { order_by => { ahr => "request_time" } }
338         );
339         
340         if( ! $self->api_name =~ /id_list/ ) {
341                 for my $hold ( @$holds ) {
342                         $hold->transit(
343                                 $apputils->simplereq(
344                                         'open-ils.cstore',
345                                         "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
346                                         { hold => $hold->id },
347                                         { order_by => { ahtc => 'id desc' }, limit => 1 }
348                                 )->[0]
349                         );
350                 }
351         }
352
353         if( $self->api_name =~ /id_list/ ) {
354                 return [ map { $_->id } @$holds ];
355         } else {
356                 return $holds;
357         }
358 }
359
360
361 __PACKAGE__->register_method(
362    method => 'user_hold_count',
363    api_name => 'open-ils.circ.hold.user.count');
364
365 sub user_hold_count {
366    my( $self, $conn, $auth, $userid ) = @_;
367    my $e = new_editor(authtoken=>$auth);
368    return $e->event unless $e->checkauth;
369    my $patron = $e->retrieve_actor_user($userid)
370       or return $e->event;
371    return $e->event unless $e->allowed('VIEW_HOLD', $patron->home_ou);
372    return __user_hold_count($self, $e, $userid);
373 }
374
375 sub __user_hold_count {
376    my( $self, $e, $userid ) = @_;
377    my $holds = $e->search_action_hold_request(
378       {  usr =>  $userid , 
379          fulfillment_time => undef,
380          cancel_time => undef,
381       }, 
382       {idlist => 1}
383    );
384
385    return scalar(@$holds);
386 }
387
388
389 __PACKAGE__->register_method(
390         method  => "retrieve_holds_by_pickup_lib",
391         api_name        => "open-ils.circ.holds.retrieve_by_pickup_lib",
392         notes           => <<NOTE);
393 Retrieves all the holds, with hold transits attached, for the specified
394 pickup_ou id. 
395 NOTE
396
397 __PACKAGE__->register_method(
398         method  => "retrieve_holds_by_pickup_lib",
399         api_name        => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
400         notes           => <<NOTE);
401 Retrieves all the hold ids for the specified
402 pickup_ou id. 
403 NOTE
404
405 sub retrieve_holds_by_pickup_lib {
406         my($self, $client, $login_session, $ou_id) = @_;
407
408         #FIXME -- put an appropriate permission check here
409         #my( $user, $target, $evt ) = $apputils->checkses_requestor(
410         #       $login_session, $user_id, 'VIEW_HOLD' );
411         #return $evt if $evt;
412
413         my $holds = $apputils->simplereq(
414                 'open-ils.cstore',
415                 "open-ils.cstore.direct.action.hold_request.search.atomic",
416                 { 
417                         pickup_lib =>  $ou_id , 
418                         fulfillment_time => undef,
419                         cancel_time => undef
420                 }, 
421                 { order_by => { ahr => "request_time" } });
422
423
424         if( ! $self->api_name =~ /id_list/ ) {
425                 flesh_hold_transits($holds);
426         }
427
428         if( $self->api_name =~ /id_list/ ) {
429                 return [ map { $_->id } @$holds ];
430         } else {
431                 return $holds;
432         }
433 }
434
435 __PACKAGE__->register_method(
436         method  => "cancel_hold",
437         api_name        => "open-ils.circ.hold.cancel",
438         notes           => <<"  NOTE");
439         Cancels the specified hold.  The login session
440         is the requestor and if the requestor is different from the usr field
441         on the hold, the requestor must have CANCEL_HOLDS permissions.
442         the hold may be either the hold object or the hold id
443         NOTE
444
445 sub cancel_hold {
446         my($self, $client, $auth, $holdid) = @_;
447
448         my $e = new_editor(authtoken=>$auth, xact=>1);
449         return $e->event unless $e->checkauth;
450
451         my $hold = $e->retrieve_action_hold_request($holdid)
452                 or return $e->event;
453
454         if( $e->requestor->id ne $hold->usr ) {
455                 return $e->event unless $e->allowed('CANCEL_HOLDS');
456         }
457
458         return 1 if $hold->cancel_time;
459
460         # If the hold is captured, reset the copy status
461         if( $hold->capture_time and $hold->current_copy ) {
462
463                 my $copy = $e->retrieve_asset_copy($hold->current_copy)
464                         or return $e->event;
465
466                 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
467          $logger->info("canceling hold $holdid whose item is on the holds shelf");
468 #                       $logger->info("setting copy to status 'reshelving' on hold cancel");
469 #                       $copy->status(OILS_COPY_STATUS_RESHELVING);
470 #                       $copy->editor($e->requestor->id);
471 #                       $copy->edit_date('now');
472 #                       $e->update_asset_copy($copy) or return $e->event;
473
474                 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
475
476                         my $hid = $hold->id;
477                         $logger->warn("! canceling hold [$hid] that is in transit");
478                         my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
479
480                         if( $transid ) {
481                                 my $trans = $e->retrieve_action_transit_copy($transid);
482                                 # Leave the transit alive, but  set the copy status to 
483                                 # reshelving so it will be properly reshelved when it gets back home
484                                 if( $trans ) {
485                                         $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
486                                         $e->update_action_transit_copy($trans) or return $e->die_event;
487                                 }
488                         }
489                 }
490         }
491
492         $hold->cancel_time('now');
493         $e->update_action_hold_request($hold)
494                 or return $e->event;
495
496         delete_hold_copy_maps($self, $e, $hold->id);
497
498         $e->commit;
499         return 1;
500 }
501
502 sub delete_hold_copy_maps {
503         my $class = shift;
504         my $editor = shift;
505         my $holdid = shift;
506
507         my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
508         for(@$maps) {
509                 $editor->delete_action_hold_copy_map($_) 
510                         or return $editor->event;
511         }
512         return undef;
513 }
514
515
516 __PACKAGE__->register_method(
517         method  => "update_hold",
518         api_name        => "open-ils.circ.hold.update",
519         notes           => <<"  NOTE");
520         Updates the specified hold.  The login session
521         is the requestor and if the requestor is different from the usr field
522         on the hold, the requestor must have UPDATE_HOLDS permissions.
523         NOTE
524
525 sub update_hold {
526         my($self, $client, $auth, $hold) = @_;
527
528     my $e = new_editor(authtoken=>$auth, xact=>1);
529     return $e->die_event unless $e->checkauth;
530
531     my $orig_hold = $e->retrieve_action_hold_request($hold->id)
532         or return $e->die_event;
533
534     # don't allow the user to be changed
535     return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
536
537     if($hold->usr ne $e->requestor->id) {
538         # if the hold is for a different user, make sure the 
539         # requestor has the appropriate permissions
540         my $usr = $e->retrieve_actor_user($hold->usr)
541             or return $e->die_event;
542         return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
543     }
544
545     update_hold_if_frozen($self, $e, $hold, $orig_hold);
546     $e->update_action_hold_request($hold) or return $e->die_event;
547     $e->commit;
548     return $hold->id;
549 }
550
551
552 # if the hold is frozen, this method ensures that the hold is not "targeted", 
553 # that is, it clears the current_copy and prev_check_time to essentiallly 
554 # reset the hold.  If it is being activated, it runs the targeter in the background
555 sub update_hold_if_frozen {
556     my($self, $e, $hold, $orig_hold) = @_;
557     return if $hold->capture_time;
558
559     if($U->is_true($hold->frozen)) {
560         $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
561         $hold->clear_current_copy;
562         $hold->clear_prev_check_time;
563
564     } else {
565         if($U->is_true($orig_hold->frozen)) {
566             $logger->info("Running targeter on activated hold ".$hold->id);
567                 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
568         }
569     }
570 }
571
572
573 __PACKAGE__->register_method(
574         method  => "retrieve_hold_status",
575         api_name        => "open-ils.circ.hold.status.retrieve",
576         notes           => <<"  NOTE");
577         Calculates the current status of the hold.
578         the requestor must have VIEW_HOLD permissions if the hold is for a user
579         other than the requestor.
580         Returns -1  on error (for now)
581         Returns 1 for 'waiting for copy to become available'
582         Returns 2 for 'waiting for copy capture'
583         Returns 3 for 'in transit'
584         Returns 4 for 'arrived'
585         NOTE
586
587 sub retrieve_hold_status {
588         my($self, $client, $auth, $hold_id) = @_;
589
590         my $e = new_editor(authtoken => $auth);
591         return $e->event unless $e->checkauth;
592         my $hold = $e->retrieve_action_hold_request($hold_id)
593                 or return $e->event;
594
595         if( $e->requestor->id != $hold->usr ) {
596                 return $e->event unless $e->allowed('VIEW_HOLD');
597         }
598
599         return _hold_status($e, $hold);
600
601 }
602
603 sub _hold_status {
604         my($e, $hold) = @_;
605         return 1 unless $hold->current_copy;
606         return 2 unless $hold->capture_time;
607
608         my $copy = $hold->current_copy;
609         unless( ref $copy ) {
610                 $copy = $e->retrieve_asset_copy($hold->current_copy)
611                         or return $e->event;
612         }
613
614         return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
615         return 4 if $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF;
616
617         return -1;
618 }
619
620
621 #sub find_local_hold {
622 #       my( $class, $session, $copy, $user ) = @_;
623 #       return $class->find_nearest_permitted_hold($session, $copy, $user);
624 #}
625
626
627 sub fetch_open_hold_by_current_copy {
628         my $class = shift;
629         my $copyid = shift;
630         my $hold = $apputils->simplereq(
631                 'open-ils.cstore', 
632                 'open-ils.cstore.direct.action.hold_request.search.atomic',
633                 { current_copy =>  $copyid , cancel_time => undef, fulfillment_time => undef });
634         return $hold->[0] if ref($hold);
635         return undef;
636 }
637
638 sub fetch_related_holds {
639         my $class = shift;
640         my $copyid = shift;
641         return $apputils->simplereq(
642                 'open-ils.cstore', 
643                 'open-ils.cstore.direct.action.hold_request.search.atomic',
644                 { current_copy =>  $copyid , cancel_time => undef, fulfillment_time => undef });
645 }
646
647
648 __PACKAGE__->register_method (
649         method          => "hold_pull_list",
650         api_name                => "open-ils.circ.hold_pull_list.retrieve",
651         signature       => q/
652                 Returns a list of holds that need to be "pulled"
653                 by a given location
654         /
655 );
656
657 __PACKAGE__->register_method (
658         method          => "hold_pull_list",
659         api_name                => "open-ils.circ.hold_pull_list.id_list.retrieve",
660         signature       => q/
661                 Returns a list of hold ID's that need to be "pulled"
662                 by a given location
663         /
664 );
665
666
667 sub hold_pull_list {
668         my( $self, $conn, $authtoken, $limit, $offset ) = @_;
669         my( $reqr, $evt ) = $U->checkses($authtoken);
670         return $evt if $evt;
671
672         my $org = $reqr->ws_ou || $reqr->home_ou;
673         # the perm locaiton shouldn't really matter here since holds
674         # will exist all over and VIEW_HOLDS should be universal
675         $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
676         return $evt if $evt;
677
678         if( $self->api_name =~ /id_list/ ) {
679                 return $U->storagereq(
680                         'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.atomic',
681                         $org, $limit, $offset ); 
682         } else {
683                 return $U->storagereq(
684                         'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.atomic',
685                         $org, $limit, $offset ); 
686         }
687 }
688
689 __PACKAGE__->register_method (
690         method          => 'fetch_hold_notify',
691         api_name                => 'open-ils.circ.hold_notification.retrieve_by_hold',
692         signature       => q/ 
693                 Returns a list of hold notification objects based on hold id.
694                 @param authtoken The loggin session key
695                 @param holdid The id of the hold whose notifications we want to retrieve
696                 @return An array of hold notification objects, event on error.
697         /
698 );
699
700 sub fetch_hold_notify {
701         my( $self, $conn, $authtoken, $holdid ) = @_;
702         my( $requestor, $evt ) = $U->checkses($authtoken);
703         return $evt if $evt;
704         my ($hold, $patron);
705         ($hold, $evt) = $U->fetch_hold($holdid);
706         return $evt if $evt;
707         ($patron, $evt) = $U->fetch_user($hold->usr);
708         return $evt if $evt;
709
710         $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
711         return $evt if $evt;
712
713         $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
714         return $U->cstorereq(
715                 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
716 }
717
718
719 __PACKAGE__->register_method (
720         method          => 'create_hold_notify',
721         api_name                => 'open-ils.circ.hold_notification.create',
722         signature       => q/
723                 Creates a new hold notification object
724                 @param authtoken The login session key
725                 @param notification The hold notification object to create
726                 @return ID of the new object on success, Event on error
727                 /
728 );
729 =head old
730 sub __create_hold_notify {
731         my( $self, $conn, $authtoken, $notification ) = @_;
732         my( $requestor, $evt ) = $U->checkses($authtoken);
733         return $evt if $evt;
734         my ($hold, $patron);
735         ($hold, $evt) = $U->fetch_hold($notification->hold);
736         return $evt if $evt;
737         ($patron, $evt) = $U->fetch_user($hold->usr);
738         return $evt if $evt;
739
740         # XXX perm depth probably doesn't matter here -- should always be consortium level
741         $evt = $U->check_perms($requestor->id, $patron->home_ou, 'CREATE_HOLD_NOTIFICATION');
742         return $evt if $evt;
743
744         # Set the proper notifier 
745         $notification->notify_staff($requestor->id);
746         my $id = $U->storagereq(
747                 'open-ils.storage.direct.action.hold_notification.create', $notification );
748         return $U->DB_UPDATE_FAILED($notification) unless $id;
749         $logger->info("User ".$requestor->id." successfully created new hold notification $id");
750         return $id;
751 }
752 =cut
753
754 sub create_hold_notify {
755    my( $self, $conn, $auth, $note ) = @_;
756    my $e = new_editor(authtoken=>$auth, xact=>1);
757    return $e->die_event unless $e->checkauth;
758
759    my $hold = $e->retrieve_action_hold_request($note->hold)
760       or return $e->die_event;
761    my $patron = $e->retrieve_actor_user($hold->usr) 
762       or return $e->die_event;
763
764    return $e->die_event unless 
765       $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
766
767         $note->notify_staff($e->requestor->id);
768    $e->create_action_hold_notification($note) or return $e->die_event;
769    $e->commit;
770    return $note->id;
771 }
772
773
774 __PACKAGE__->register_method(
775         method  => 'reset_hold',
776         api_name        => 'open-ils.circ.hold.reset',
777         signature       => q/
778                 Un-captures and un-targets a hold, essentially returning
779                 it to the state it was in directly after it was placed,
780                 then attempts to re-target the hold
781                 @param authtoken The login session key
782                 @param holdid The id of the hold
783         /
784 );
785
786
787 sub reset_hold {
788         my( $self, $conn, $auth, $holdid ) = @_;
789         my $reqr;
790         my ($hold, $evt) = $U->fetch_hold($holdid);
791         return $evt if $evt;
792         ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD'); # XXX stronger permission
793         return $evt if $evt;
794         $evt = _reset_hold($self, $reqr, $hold);
795         return $evt if $evt;
796         return 1;
797 }
798
799 sub _reset_hold {
800         my ($self, $reqr, $hold) = @_;
801
802         my $e = new_editor(xact =>1, requestor => $reqr);
803
804         $logger->info("reseting hold ".$hold->id);
805
806         my $hid = $hold->id;
807
808         if( $hold->capture_time and $hold->current_copy ) {
809
810                 my $copy = $e->retrieve_asset_copy($hold->current_copy)
811                         or return $e->event;
812
813                 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
814                         $logger->info("setting copy to status 'reshelving' on hold retarget");
815                         $copy->status(OILS_COPY_STATUS_RESHELVING);
816                         $copy->editor($e->requestor->id);
817                         $copy->edit_date('now');
818                         $e->update_asset_copy($copy) or return $e->event;
819
820                 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
821
822                         # We don't want the copy to remain "in transit"
823                         $copy->status(OILS_COPY_STATUS_RESHELVING);
824                         $logger->warn("! reseting hold [$hid] that is in transit");
825                         my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
826
827                         if( $transid ) {
828                                 my $trans = $e->retrieve_action_transit_copy($transid);
829                                 if( $trans ) {
830                                         $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
831                                         my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1);
832                                         $logger->info("Transit abort completed with result $evt");
833                                         return $evt unless "$evt" eq 1;
834                                 }
835                         }
836                 }
837         }
838
839         $hold->clear_capture_time;
840         $hold->clear_current_copy;
841
842         $e->update_action_hold_request($hold) or return $e->event;
843         $e->commit;
844
845         $U->storagereq(
846                 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
847
848         return undef;
849 }
850
851
852 __PACKAGE__->register_method(
853         method => 'fetch_open_title_holds',
854         api_name        => 'open-ils.circ.open_holds.retrieve',
855         signature       => q/
856                 Returns a list ids of un-fulfilled holds for a given title id
857                 @param authtoken The login session key
858                 @param id the id of the item whose holds we want to retrieve
859                 @param type The hold type - M, T, V, C
860         /
861 );
862
863 sub fetch_open_title_holds {
864         my( $self, $conn, $auth, $id, $type, $org ) = @_;
865         my $e = new_editor( authtoken => $auth );
866         return $e->event unless $e->checkauth;
867
868         $type ||= "T";
869         $org ||= $e->requestor->ws_ou;
870
871 #       return $e->search_action_hold_request(
872 #               { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
873
874         # XXX make me return IDs in the future ^--
875         my $holds = $e->search_action_hold_request(
876                 { 
877                         target                          => $id, 
878                         cancel_time                     => undef, 
879                         hold_type                       => $type, 
880                         fulfillment_time        => undef 
881                 }
882         );
883
884         flesh_hold_transits($holds);
885         return $holds;
886 }
887
888
889 sub flesh_hold_transits {
890         my $holds = shift;
891         for my $hold ( @$holds ) {
892                 $hold->transit(
893                         $apputils->simplereq(
894                                 'open-ils.cstore',
895                                 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
896                                 { hold => $hold->id },
897                                 { order_by => { ahtc => 'id desc' }, limit => 1 }
898                         )->[0]
899                 );
900         }
901 }
902
903 sub flesh_hold_notices {
904         my( $holds, $e ) = @_;
905         $e ||= new_editor();
906
907         for my $hold (@$holds) {
908                 my $notices = $e->search_action_hold_notification(
909                         [
910                                 { hold => $hold->id },
911                                 { order_by => { anh => 'notify_time desc' } },
912                         ],
913                         {idlist=>1}
914                 );
915
916                 $hold->notify_count(scalar(@$notices));
917                 if( @$notices ) {
918                         my $n = $e->retrieve_action_hold_notification($$notices[0])
919                                 or return $e->event;
920                         $hold->notify_time($n->notify_time);
921                 }
922         }
923 }
924
925
926
927
928 __PACKAGE__->register_method(
929         method => 'fetch_captured_holds',
930         api_name        => 'open-ils.circ.captured_holds.on_shelf.retrieve',
931         signature       => q/
932                 Returns a list of un-fulfilled holds for a given title id
933                 @param authtoken The login session key
934                 @param org The org id of the location in question
935         /
936 );
937
938 __PACKAGE__->register_method(
939         method => 'fetch_captured_holds',
940         api_name        => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
941         signature       => q/
942                 Returns a list ids of un-fulfilled holds for a given title id
943                 @param authtoken The login session key
944                 @param org The org id of the location in question
945         /
946 );
947
948 sub fetch_captured_holds {
949         my( $self, $conn, $auth, $org ) = @_;
950
951         my $e = new_editor(authtoken => $auth);
952         return $e->event unless $e->checkauth;
953         return $e->event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
954
955         $org ||= $e->requestor->ws_ou;
956
957         my $holds = $e->search_action_hold_request(
958                 { 
959                         capture_time            => { "!=" => undef },
960                         current_copy            => { "!=" => undef },
961                         fulfillment_time        => undef,
962                         pickup_lib                      => $org,
963                         cancel_time                     => undef,
964                 }
965         );
966
967         my @res;
968         for my $h (@$holds) {
969                 my $copy = $e->retrieve_asset_copy($h->current_copy)
970                         or return $e->event;
971                 push( @res, $h ) if 
972                         $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF;
973         }
974
975         if( ! $self->api_name =~ /id_list/ ) {
976                 flesh_hold_transits(\@res);
977                 flesh_hold_notices(\@res, $e);
978         }
979
980         if( $self->api_name =~ /id_list/ ) {
981                 return [ map { $_->id } @res ];
982         } else {
983                 return \@res;
984         }
985 }
986
987 __PACKAGE__->register_method(
988         method  => "check_title_hold",
989         api_name        => "open-ils.circ.title_hold.is_possible",
990         notes           => q/
991                 Determines if a hold were to be placed by a given user,
992                 whether or not said hold would have any potential copies
993                 to fulfill it.
994                 @param authtoken The login session key
995                 @param params A hash of named params including:
996                         patronid  - the id of the hold recipient
997                         titleid (brn) - the id of the title to be held
998                         depth   - the hold range depth (defaults to 0)
999         /);
1000
1001 sub check_title_hold {
1002         my( $self, $client, $authtoken, $params ) = @_;
1003
1004         my %params              = %$params;
1005         my $titleid             = $params{titleid} ||"";
1006         my $volid               = $params{volume_id};
1007         my $copyid              = $params{copy_id};
1008         my $mrid                = $params{mrid} ||"";
1009         my $depth               = $params{depth} || 0;
1010         my $pickup_lib  = $params{pickup_lib};
1011         my $hold_type   = $params{hold_type} || 'T';
1012     my $selection_ou = $params{selection_ou} || $pickup_lib;
1013
1014         my $e = new_editor(authtoken=>$authtoken);
1015         return $e->event unless $e->checkauth;
1016         my $patron = $e->retrieve_actor_user($params{patronid})
1017                 or return $e->event;
1018
1019         if( $e->requestor->id ne $patron->id ) {
1020                 return $e->event unless 
1021                         $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
1022         }
1023
1024         return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
1025
1026         my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
1027                 or return $e->event;
1028
1029     my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
1030     my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
1031
1032     if(defined $soft_boundary and $$params{depth} < $soft_boundary) {
1033         # work up the tree and as soon as we find a potential copy, use that depth
1034         # also, make sure we don't go past the hard boundary if it exists
1035
1036         # our min boundary is the greater of user-specified boundary or hard boundary
1037         my $min_depth = (defined $hard_boundary and $hard_boundary > $$params{depth}) ?  
1038             $hard_boundary : $$params{depth};
1039
1040         my $depth = $soft_boundary;
1041         while($depth >= $min_depth) {
1042             $logger->info("performing hold possibility check with soft boundary $depth");
1043             return {success => 1, depth => $depth}
1044                 if do_possibility_checks($e, $patron, $request_lib, $depth, %params);
1045             $depth--;
1046         }
1047         return {success => 0};
1048
1049     } elsif(defined $hard_boundary and $$params{depth} < $hard_boundary) {
1050         # there is no soft boundary, enforce the hard boundary if it exists
1051         $logger->info("performing hold possibility check with hard boundary $hard_boundary");
1052         if(do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params)) {
1053             return {success => 1, depth => $hard_boundary}
1054         } else {
1055             return {success => 0};
1056         }
1057
1058     } else {
1059         # no boundaries defined, fall back to user specifed boundary or no boundary
1060         $logger->info("performing hold possibility check with no boundary");
1061         if(do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params)) {
1062             return {success => 1, depth => $hard_boundary};
1063         } else {
1064             return {success => 0};
1065         }
1066     }
1067 }
1068
1069 sub do_possibility_checks {
1070     my($e, $patron, $request_lib, $depth, %params) = @_;
1071
1072         my $titleid             = $params{titleid} ||"";
1073         my $volid               = $params{volume_id};
1074         my $copyid              = $params{copy_id};
1075         my $mrid                = $params{mrid} ||"";
1076         my $pickup_lib  = $params{pickup_lib};
1077         my $hold_type   = $params{hold_type} || 'T';
1078     my $selection_ou = $params{selection_ou} || $pickup_lib;
1079
1080
1081         my $copy;
1082         my $volume;
1083         my $title;
1084
1085         if( $hold_type eq OILS_HOLD_TYPE_COPY ) {
1086
1087                 $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
1088                 $volume = $e->retrieve_asset_call_number($copy->call_number)
1089                         or return $e->event;
1090                 $title = $e->retrieve_biblio_record_entry($volume->record)
1091                         or return $e->event;
1092                 return verify_copy_for_hold( 
1093                         $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib );
1094
1095         } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
1096
1097                 $volume = $e->retrieve_asset_call_number($volid)
1098                         or return $e->event;
1099                 $title = $e->retrieve_biblio_record_entry($volume->record)
1100                         or return $e->event;
1101
1102                 return _check_volume_hold_is_possible(
1103                         $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou);
1104
1105         } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
1106
1107                 return _check_title_hold_is_possible(
1108                         $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou);
1109
1110         } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
1111
1112                 my $maps = $e->search_metabib_source_map({metarecord=>$mrid});
1113                 my @recs = map { $_->source } @$maps;
1114                 for my $rec (@recs) {
1115                         return 1 if (_check_title_hold_is_possible(
1116                                 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou));
1117                 }
1118                 return 0;       
1119         }
1120 }
1121
1122 my %prox_cache;
1123
1124 sub _check_metarecord_hold_is_possible {
1125         my( $mrid, $rangelib, $depth, $request_lib, $patron, $requestor, $pickup_lib ) = @_;
1126    
1127    my $e = new_editor();
1128
1129     # this monster will grab the id and circ_lib of all of the "holdable" copies for the given metarecord
1130     my $copies = $e->json_query(
1131         { 
1132             select => { acp => ['id', 'circ_lib'] },
1133             from => {
1134                 acp => {
1135                     acn => {
1136                         field => 'id',
1137                         fkey => 'call_number',
1138                         'join' => {
1139                             mmrsm => {
1140                                 field => 'source',
1141                                 fkey => 'record',
1142                                 filter => { metarecord => $mrid }
1143                             }
1144                         }
1145                     },
1146                     acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
1147                     ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
1148                 }
1149             }, 
1150             where => {
1151                 '+acp' => { circulate => 't', deleted => 'f', holdable => 't' }
1152             }
1153         }
1154     );
1155
1156    return $e->event unless defined $copies;
1157    $logger->info("metarecord possible found ".scalar(@$copies)." potential copies");
1158    return 0 unless @$copies;
1159
1160    # -----------------------------------------------------------------------
1161    # sort the copies into buckets based on their circ_lib proximity to 
1162    # the patron's home_ou.  
1163    # -----------------------------------------------------------------------
1164
1165    my $home_org = $patron->home_ou;
1166    my $req_org = $request_lib->id;
1167
1168    my $home_prox = 
1169       ($prox_cache{$home_org}) ? 
1170          $prox_cache{$home_org} :
1171          $prox_cache{$home_org} = $e->search_actor_org_unit_proximity({from_org => $home_org});
1172
1173    my %buckets;
1174    my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
1175    push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1176
1177    my @keys = sort { $a <=> $b } keys %buckets;
1178
1179
1180    if( $home_org ne $req_org ) {
1181       # -----------------------------------------------------------------------
1182       # shove the copies close to the request_lib into the primary buckets 
1183       # directly before the farthest away copies.  That way, they are not 
1184       # given priority, but they are checked before the farthest copies.
1185       # -----------------------------------------------------------------------
1186       my $req_prox = 
1187          ($prox_cache{$req_org}) ? 
1188             $prox_cache{$req_org} :
1189             $prox_cache{$req_org} = $e->search_actor_org_unit_proximity({from_org => $req_org});
1190
1191       my %buckets2;
1192       my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
1193       push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1194
1195       my $highest_key = $keys[@keys - 1];  # the farthest prox in the exising buckets
1196       my $new_key = $highest_key - 0.5; # right before the farthest prox
1197       my @keys2 = sort { $a <=> $b } keys %buckets2;
1198       for my $key (@keys2) {
1199          last if $key >= $highest_key;
1200          push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
1201       }
1202    }
1203
1204    @keys = sort { $a <=> $b } keys %buckets;
1205
1206    my %seen;
1207    for my $key (@keys) {
1208       my @cps = @{$buckets{$key}};
1209
1210       $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
1211
1212       for my $copyid (@cps) {
1213
1214          next if $seen{$copyid};
1215          $seen{$copyid} = 1; # there could be dupes given the merged buckets
1216          my $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
1217          $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
1218
1219          my $vol = $e->retrieve_asset_call_number(
1220            [ $copy->call_number, { flesh => 1, flesh_fields => { acn => ['record'] } } ] );
1221
1222          return 1 if verify_copy_for_hold( 
1223             $patron, $requestor, $vol->record, $copy, $pickup_lib, $request_lib );
1224    
1225       }
1226    }
1227
1228    return 0;
1229 }
1230
1231 sub create_ranged_org_filter {
1232     my($e, $selection_ou, $depth) = @_;
1233
1234     # find the orgs from which this hold may be fulfilled, 
1235     # based on the selection_ou and depth
1236
1237     my $top_org = $e->search_actor_org_unit([
1238         {parent_ou => undef}, 
1239         {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
1240     my %org_filter;
1241
1242     return () if $depth == $top_org->ou_type->depth;
1243
1244     my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
1245     %org_filter = (circ_lib => []);
1246     push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
1247
1248     $logger->info("hold org filter at depth $depth and selection_ou ".
1249         "$selection_ou created list of @{$org_filter{circ_lib}}");
1250
1251     return %org_filter;
1252 }
1253
1254
1255 sub _check_title_hold_is_possible {
1256         my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
1257    
1258     my $e = new_editor();
1259     my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
1260
1261     # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
1262     my $copies = $e->json_query(
1263         { 
1264             select => { acp => ['id', 'circ_lib'] },
1265             from => {
1266                 acp => {
1267                     acn => {
1268                         field => 'id',
1269                         fkey => 'call_number',
1270                         'join' => {
1271                             bre => {
1272                                 field => 'id',
1273                                 filter => { id => $titleid },
1274                                 fkey => 'record'
1275                             }
1276                         }
1277                     },
1278                     acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
1279                     ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
1280                 }
1281             }, 
1282             where => {
1283                 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
1284             }
1285         }
1286     );
1287
1288    return $e->event unless defined $copies;
1289    $logger->info("title possible found ".scalar(@$copies)." potential copies");
1290    return 0 unless @$copies;
1291
1292    # -----------------------------------------------------------------------
1293    # sort the copies into buckets based on their circ_lib proximity to 
1294    # the patron's home_ou.  
1295    # -----------------------------------------------------------------------
1296
1297    my $home_org = $patron->home_ou;
1298    my $req_org = $request_lib->id;
1299
1300    my $home_prox = 
1301       ($prox_cache{$home_org}) ? 
1302          $prox_cache{$home_org} :
1303          $prox_cache{$home_org} = $e->search_actor_org_unit_proximity({from_org => $home_org});
1304
1305    my %buckets;
1306    my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
1307    push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1308
1309    my @keys = sort { $a <=> $b } keys %buckets;
1310
1311
1312    if( $home_org ne $req_org ) {
1313       # -----------------------------------------------------------------------
1314       # shove the copies close to the request_lib into the primary buckets 
1315       # directly before the farthest away copies.  That way, they are not 
1316       # given priority, but they are checked before the farthest copies.
1317       # -----------------------------------------------------------------------
1318       my $req_prox = 
1319          ($prox_cache{$req_org}) ? 
1320             $prox_cache{$req_org} :
1321             $prox_cache{$req_org} = $e->search_actor_org_unit_proximity({from_org => $req_org});
1322
1323       my %buckets2;
1324       my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
1325       push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1326
1327       my $highest_key = $keys[@keys - 1];  # the farthest prox in the exising buckets
1328       my $new_key = $highest_key - 0.5; # right before the farthest prox
1329       my @keys2 = sort { $a <=> $b } keys %buckets2;
1330       for my $key (@keys2) {
1331          last if $key >= $highest_key;
1332          push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
1333       }
1334    }
1335
1336    @keys = sort { $a <=> $b } keys %buckets;
1337
1338    my $title;
1339    my %seen;
1340    for my $key (@keys) {
1341       my @cps = @{$buckets{$key}};
1342
1343       $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
1344
1345       for my $copyid (@cps) {
1346
1347          next if $seen{$copyid};
1348          $seen{$copyid} = 1; # there could be dupes given the merged buckets
1349          my $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
1350          $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
1351
1352          unless($title) { # grab the title if we don't already have it
1353             my $vol = $e->retrieve_asset_call_number(
1354                [ $copy->call_number, { flesh => 1, flesh_fields => { acn => ['record'] } } ] );
1355             $title = $vol->record;
1356          }
1357    
1358          return 1 if verify_copy_for_hold( 
1359             $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
1360    
1361       }
1362    }
1363
1364    return 0;
1365 }
1366
1367
1368 sub _check_volume_hold_is_possible {
1369         my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
1370     my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
1371         my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
1372         $logger->info("checking possibility of volume hold for volume ".$vol->id);
1373         for my $copy ( @$copies ) {
1374                 return 1 if verify_copy_for_hold( 
1375                         $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
1376         }
1377         return 0;
1378 }
1379
1380
1381
1382 sub verify_copy_for_hold {
1383         my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib ) = @_;
1384         $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
1385         return 1 if OpenILS::Utils::PermitHold::permit_copy_hold(
1386                 {       patron                          => $patron, 
1387                         requestor                       => $requestor, 
1388                         copy                            => $copy,
1389                         title                           => $title, 
1390                         title_descriptor        => $title->fixed_fields, # this is fleshed into the title object
1391                         pickup_lib                      => $pickup_lib,
1392                         request_lib                     => $request_lib,
1393             new_hold            => 1
1394                 } 
1395         );
1396         return 0;
1397 }
1398
1399
1400
1401 sub find_nearest_permitted_hold {
1402
1403         my $class       = shift;
1404         my $editor      = shift; # CStoreEditor object
1405         my $copy                = shift; # copy to target
1406         my $user                = shift; # staff 
1407         my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
1408         my $evt         = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
1409
1410         my $bc = $copy->barcode;
1411
1412         # find any existing holds that already target this copy
1413         my $old_holds = $editor->search_action_hold_request(
1414                 {       current_copy => $copy->id, 
1415                         cancel_time => undef, 
1416                         capture_time => undef 
1417                 } 
1418         );
1419
1420         # hold->type "R" means we need this copy
1421         for my $h (@$old_holds) { return ($h) if $h->hold_type eq 'R'; }
1422
1423
1424     my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
1425
1426         $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
1427         " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
1428
1429         # search for what should be the best holds for this copy to fulfill
1430         my $best_holds = $U->storagereq(
1431                 "open-ils.storage.action.hold_request.nearest_hold.atomic",
1432                 $user->ws_ou, $copy->id, 10, $hold_stall_interval );
1433
1434         unless(@$best_holds) {
1435
1436                 if( my $hold = $$old_holds[0] ) {
1437                         $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
1438                         return ($hold);
1439                 }
1440
1441                 $logger->info("circulator: no suitable holds found for copy $bc");
1442                 return (undef, $evt);
1443         }
1444
1445
1446         my $best_hold;
1447
1448         # for each potential hold, we have to run the permit script
1449         # to make sure the hold is actually permitted.
1450         for my $holdid (@$best_holds) {
1451                 next unless $holdid;
1452                 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
1453
1454                 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
1455                 my $reqr = $editor->retrieve_actor_user($hold->requestor) or next;
1456                 my $rlib = $editor->retrieve_actor_org_unit($hold->request_lib) or next;
1457
1458                 # see if this hold is permitted
1459                 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
1460                         {       patron_id                       => $hold->usr,
1461                                 requestor                       => $reqr,
1462                                 copy                            => $copy,
1463                                 pickup_lib                      => $hold->pickup_lib,
1464                                 request_lib                     => $rlib,
1465                         } 
1466                 );
1467
1468                 if( $permitted ) {
1469                         $best_hold = $hold;
1470                         last;
1471                 }
1472         }
1473
1474
1475         unless( $best_hold ) { # no "good" permitted holds were found
1476                 if( my $hold = $$old_holds[0] ) { # can we return a pre-targeted hold?
1477                         $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
1478                         return ($hold);
1479                 }
1480
1481                 # we got nuthin
1482                 $logger->info("circulator: no suitable holds found for copy $bc");
1483                 return (undef, $evt);
1484         }
1485
1486         $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
1487
1488         # indicate a permitted hold was found
1489         return $best_hold if $check_only;
1490
1491         # we've found a permitted hold.  we need to "grab" the copy 
1492         # to prevent re-targeted holds (next part) from re-grabbing the copy
1493         $best_hold->current_copy($copy->id);
1494         $editor->update_action_hold_request($best_hold) 
1495                 or return (undef, $editor->event);
1496
1497
1498     my $retarget = 0;
1499
1500         # re-target any other holds that already target this copy
1501         for my $old_hold (@$old_holds) {
1502                 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
1503                 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
1504             $old_hold->id." after a better hold [".$best_hold->id."] was found");
1505         $old_hold->clear_current_copy;
1506         $old_hold->clear_prev_check_time;
1507         $editor->update_action_hold_request($old_hold) 
1508             or return (undef, $editor->event);
1509         $retarget = 1;
1510         }
1511
1512         return ($best_hold, undef, $retarget);
1513 }
1514
1515
1516
1517
1518
1519
1520 __PACKAGE__->register_method(
1521         method => 'all_rec_holds',
1522         api_name => 'open-ils.circ.holds.retrieve_all_from_title',
1523 );
1524
1525 sub all_rec_holds {
1526         my( $self, $conn, $auth, $title_id, $args ) = @_;
1527
1528         my $e = new_editor(authtoken=>$auth);
1529         $e->checkauth or return $e->event;
1530         $e->allowed('VIEW_HOLD') or return $e->event;
1531
1532         $args ||= { fulfillment_time => undef };
1533         $args->{cancel_time} = undef;
1534
1535         my $resp = { volume_holds => [], copy_holds => [] };
1536
1537         $resp->{title_holds} = $e->search_action_hold_request(
1538                 { 
1539                         hold_type => OILS_HOLD_TYPE_TITLE, 
1540                         target => $title_id, 
1541                         %$args 
1542                 }, {idlist=>1} );
1543
1544         my $vols = $e->search_asset_call_number(
1545                 { record => $title_id, deleted => 'f' }, {idlist=>1});
1546
1547         return $resp unless @$vols;
1548
1549         $resp->{volume_holds} = $e->search_action_hold_request(
1550                 { 
1551                         hold_type => OILS_HOLD_TYPE_VOLUME, 
1552                         target => $vols,
1553                         %$args }, 
1554                 {idlist=>1} );
1555
1556         my $copies = $e->search_asset_copy(
1557                 { call_number => $vols, deleted => 'f' }, {idlist=>1});
1558
1559         return $resp unless @$copies;
1560
1561         $resp->{copy_holds} = $e->search_action_hold_request(
1562                 { 
1563                         hold_type => OILS_HOLD_TYPE_COPY,
1564                         target => $copies,
1565                         %$args }, 
1566                 {idlist=>1} );
1567
1568         return $resp;
1569 }
1570
1571
1572
1573
1574
1575 __PACKAGE__->register_method(
1576         method => 'uber_hold',
1577     authoritative => 1,
1578         api_name => 'open-ils.circ.hold.details.retrieve'
1579 );
1580
1581 sub uber_hold {
1582         my($self, $client, $auth, $hold_id) = @_;
1583         my $e = new_editor(authtoken=>$auth);
1584         $e->checkauth or return $e->event;
1585         $e->allowed('VIEW_HOLD') or return $e->event;
1586
1587         my $resp = {};
1588
1589         my $hold = $e->retrieve_action_hold_request(
1590                 [
1591                         $hold_id,
1592                         {
1593                                 flesh => 1,
1594                                 flesh_fields => { ahr => [ 'current_copy', 'usr' ] }
1595                         }
1596                 ]
1597         ) or return $e->event;
1598
1599         my $user = $hold->usr;
1600         $hold->usr($user->id);
1601
1602         my $card = $e->retrieve_actor_card($user->card)
1603                 or return $e->event;
1604
1605         my( $mvr, $volume, $copy ) = find_hold_mvr($e, $hold);
1606
1607         flesh_hold_notices([$hold], $e);
1608         flesh_hold_transits([$hold]);
1609
1610         return {
1611                 hold            => $hold,
1612                 copy            => $copy,
1613                 volume  => $volume,
1614                 mvr             => $mvr,
1615                 status  => _hold_status($e, $hold),
1616                 patron_first => $user->first_given_name,
1617                 patron_last  => $user->family_name,
1618                 patron_barcode => $card->barcode,
1619         };
1620 }
1621
1622
1623
1624 # -----------------------------------------------------
1625 # Returns the MVR object that represents what the
1626 # hold is all about
1627 # -----------------------------------------------------
1628 sub find_hold_mvr {
1629         my( $e, $hold ) = @_;
1630
1631         my $tid;
1632         my $copy;
1633         my $volume;
1634
1635         if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
1636                 my $mr = $e->retrieve_metabib_metarecord($hold->target)
1637                         or return $e->event;
1638                 $tid = $mr->master_record;
1639
1640         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
1641                 $tid = $hold->target;
1642
1643         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
1644                 $volume = $e->retrieve_asset_call_number($hold->target)
1645                         or return $e->event;
1646                 $tid = $volume->record;
1647
1648         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_COPY ) {
1649                 $copy = $e->retrieve_asset_copy($hold->target)
1650                         or return $e->event;
1651                 $volume = $e->retrieve_asset_call_number($copy->call_number)
1652                         or return $e->event;
1653                 $tid = $volume->record;
1654         }
1655
1656         if(!$copy and ref $hold->current_copy ) {
1657                 $copy = $hold->current_copy;
1658                 $hold->current_copy($copy->id);
1659         }
1660
1661         if(!$volume and $copy) {
1662                 $volume = $e->retrieve_asset_call_number($copy->call_number);
1663         }
1664
1665         my $title = $e->retrieve_biblio_record_entry($tid);
1666         return ( $U->record_to_mvr($title), $volume, $copy );
1667 }
1668
1669
1670
1671
1672 1;