]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ/Holds.pm
7456a86368e143bf7b6d9b2c66d649e09246d586
[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     $prox_cache{$home_org} = 
1169         $e->search_actor_org_unit_proximity({from_org => $home_org})
1170         unless $prox_cache{$home_org};
1171     my $home_prox = $prox_cache{$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
1187         $prox_cache{$req_org} = 
1188             $e->search_actor_org_unit_proximity({from_org => $req_org})
1189             unless $prox_cache{$req_org};
1190         my $req_prox = $prox_cache{$req_org};
1191
1192       my %buckets2;
1193       my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
1194       push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1195
1196       my $highest_key = $keys[@keys - 1];  # the farthest prox in the exising buckets
1197       my $new_key = $highest_key - 0.5; # right before the farthest prox
1198       my @keys2 = sort { $a <=> $b } keys %buckets2;
1199       for my $key (@keys2) {
1200          last if $key >= $highest_key;
1201          push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
1202       }
1203    }
1204
1205    @keys = sort { $a <=> $b } keys %buckets;
1206
1207    my %seen;
1208    for my $key (@keys) {
1209       my @cps = @{$buckets{$key}};
1210
1211       $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
1212
1213       for my $copyid (@cps) {
1214
1215          next if $seen{$copyid};
1216          $seen{$copyid} = 1; # there could be dupes given the merged buckets
1217          my $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
1218          $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
1219
1220          my $vol = $e->retrieve_asset_call_number(
1221            [ $copy->call_number, { flesh => 1, flesh_fields => { acn => ['record'] } } ] );
1222
1223          return 1 if verify_copy_for_hold( 
1224             $patron, $requestor, $vol->record, $copy, $pickup_lib, $request_lib );
1225    
1226       }
1227    }
1228
1229    return 0;
1230 }
1231
1232 sub create_ranged_org_filter {
1233     my($e, $selection_ou, $depth) = @_;
1234
1235     # find the orgs from which this hold may be fulfilled, 
1236     # based on the selection_ou and depth
1237
1238     my $top_org = $e->search_actor_org_unit([
1239         {parent_ou => undef}, 
1240         {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
1241     my %org_filter;
1242
1243     return () if $depth == $top_org->ou_type->depth;
1244
1245     my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
1246     %org_filter = (circ_lib => []);
1247     push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
1248
1249     $logger->info("hold org filter at depth $depth and selection_ou ".
1250         "$selection_ou created list of @{$org_filter{circ_lib}}");
1251
1252     return %org_filter;
1253 }
1254
1255
1256 sub _check_title_hold_is_possible {
1257         my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
1258    
1259     my $e = new_editor();
1260     my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
1261
1262     # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
1263     my $copies = $e->json_query(
1264         { 
1265             select => { acp => ['id', 'circ_lib'] },
1266             from => {
1267                 acp => {
1268                     acn => {
1269                         field => 'id',
1270                         fkey => 'call_number',
1271                         'join' => {
1272                             bre => {
1273                                 field => 'id',
1274                                 filter => { id => $titleid },
1275                                 fkey => 'record'
1276                             }
1277                         }
1278                     },
1279                     acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
1280                     ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
1281                 }
1282             }, 
1283             where => {
1284                 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
1285             }
1286         }
1287     );
1288
1289    return $e->event unless defined $copies;
1290    $logger->info("title possible found ".scalar(@$copies)." potential copies");
1291    return 0 unless @$copies;
1292
1293    # -----------------------------------------------------------------------
1294    # sort the copies into buckets based on their circ_lib proximity to 
1295    # the patron's home_ou.  
1296    # -----------------------------------------------------------------------
1297
1298    my $home_org = $patron->home_ou;
1299    my $req_org = $request_lib->id;
1300
1301     $logger->info("prox cache $home_org " . $prox_cache{$home_org});
1302
1303     $prox_cache{$home_org} = 
1304         $e->search_actor_org_unit_proximity({from_org => $home_org})
1305         unless $prox_cache{$home_org};
1306     my $home_prox = $prox_cache{$home_org};
1307
1308    my %buckets;
1309    my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
1310    push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1311
1312    my @keys = sort { $a <=> $b } keys %buckets;
1313
1314
1315    if( $home_org ne $req_org ) {
1316       # -----------------------------------------------------------------------
1317       # shove the copies close to the request_lib into the primary buckets 
1318       # directly before the farthest away copies.  That way, they are not 
1319       # given priority, but they are checked before the farthest copies.
1320       # -----------------------------------------------------------------------
1321         $prox_cache{$req_org} = 
1322             $e->search_actor_org_unit_proximity({from_org => $req_org})
1323             unless $prox_cache{$req_org};
1324         my $req_prox = $prox_cache{$req_org};
1325
1326
1327       my %buckets2;
1328       my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
1329       push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1330
1331       my $highest_key = $keys[@keys - 1];  # the farthest prox in the exising buckets
1332       my $new_key = $highest_key - 0.5; # right before the farthest prox
1333       my @keys2 = sort { $a <=> $b } keys %buckets2;
1334       for my $key (@keys2) {
1335          last if $key >= $highest_key;
1336          push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
1337       }
1338    }
1339
1340    @keys = sort { $a <=> $b } keys %buckets;
1341
1342    my $title;
1343    my %seen;
1344    for my $key (@keys) {
1345       my @cps = @{$buckets{$key}};
1346
1347       $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
1348
1349       for my $copyid (@cps) {
1350
1351          next if $seen{$copyid};
1352          $seen{$copyid} = 1; # there could be dupes given the merged buckets
1353          my $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
1354          $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
1355
1356          unless($title) { # grab the title if we don't already have it
1357             my $vol = $e->retrieve_asset_call_number(
1358                [ $copy->call_number, { flesh => 1, flesh_fields => { acn => ['record'] } } ] );
1359             $title = $vol->record;
1360          }
1361    
1362          return 1 if verify_copy_for_hold( 
1363             $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
1364    
1365       }
1366    }
1367
1368    return 0;
1369 }
1370
1371
1372 sub _check_volume_hold_is_possible {
1373         my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
1374     my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
1375         my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
1376         $logger->info("checking possibility of volume hold for volume ".$vol->id);
1377         for my $copy ( @$copies ) {
1378                 return 1 if verify_copy_for_hold( 
1379                         $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
1380         }
1381         return 0;
1382 }
1383
1384
1385
1386 sub verify_copy_for_hold {
1387         my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib ) = @_;
1388         $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
1389         return 1 if OpenILS::Utils::PermitHold::permit_copy_hold(
1390                 {       patron                          => $patron, 
1391                         requestor                       => $requestor, 
1392                         copy                            => $copy,
1393                         title                           => $title, 
1394                         title_descriptor        => $title->fixed_fields, # this is fleshed into the title object
1395                         pickup_lib                      => $pickup_lib,
1396                         request_lib                     => $request_lib,
1397             new_hold            => 1
1398                 } 
1399         );
1400         return 0;
1401 }
1402
1403
1404
1405 sub find_nearest_permitted_hold {
1406
1407         my $class       = shift;
1408         my $editor      = shift; # CStoreEditor object
1409         my $copy                = shift; # copy to target
1410         my $user                = shift; # staff 
1411         my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
1412         my $evt         = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
1413
1414         my $bc = $copy->barcode;
1415
1416         # find any existing holds that already target this copy
1417         my $old_holds = $editor->search_action_hold_request(
1418                 {       current_copy => $copy->id, 
1419                         cancel_time => undef, 
1420                         capture_time => undef 
1421                 } 
1422         );
1423
1424         # hold->type "R" means we need this copy
1425         for my $h (@$old_holds) { return ($h) if $h->hold_type eq 'R'; }
1426
1427
1428     my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
1429
1430         $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
1431         " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
1432
1433         # search for what should be the best holds for this copy to fulfill
1434         my $best_holds = $U->storagereq(
1435                 "open-ils.storage.action.hold_request.nearest_hold.atomic",
1436                 $user->ws_ou, $copy->id, 10, $hold_stall_interval );
1437
1438         unless(@$best_holds) {
1439
1440                 if( my $hold = $$old_holds[0] ) {
1441                         $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
1442                         return ($hold);
1443                 }
1444
1445                 $logger->info("circulator: no suitable holds found for copy $bc");
1446                 return (undef, $evt);
1447         }
1448
1449
1450         my $best_hold;
1451
1452         # for each potential hold, we have to run the permit script
1453         # to make sure the hold is actually permitted.
1454         for my $holdid (@$best_holds) {
1455                 next unless $holdid;
1456                 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
1457
1458                 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
1459                 my $reqr = $editor->retrieve_actor_user($hold->requestor) or next;
1460                 my $rlib = $editor->retrieve_actor_org_unit($hold->request_lib) or next;
1461
1462                 # see if this hold is permitted
1463                 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
1464                         {       patron_id                       => $hold->usr,
1465                                 requestor                       => $reqr,
1466                                 copy                            => $copy,
1467                                 pickup_lib                      => $hold->pickup_lib,
1468                                 request_lib                     => $rlib,
1469                         } 
1470                 );
1471
1472                 if( $permitted ) {
1473                         $best_hold = $hold;
1474                         last;
1475                 }
1476         }
1477
1478
1479         unless( $best_hold ) { # no "good" permitted holds were found
1480                 if( my $hold = $$old_holds[0] ) { # can we return a pre-targeted hold?
1481                         $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
1482                         return ($hold);
1483                 }
1484
1485                 # we got nuthin
1486                 $logger->info("circulator: no suitable holds found for copy $bc");
1487                 return (undef, $evt);
1488         }
1489
1490         $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
1491
1492         # indicate a permitted hold was found
1493         return $best_hold if $check_only;
1494
1495         # we've found a permitted hold.  we need to "grab" the copy 
1496         # to prevent re-targeted holds (next part) from re-grabbing the copy
1497         $best_hold->current_copy($copy->id);
1498         $editor->update_action_hold_request($best_hold) 
1499                 or return (undef, $editor->event);
1500
1501
1502     my $retarget = 0;
1503
1504         # re-target any other holds that already target this copy
1505         for my $old_hold (@$old_holds) {
1506                 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
1507                 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
1508             $old_hold->id." after a better hold [".$best_hold->id."] was found");
1509         $old_hold->clear_current_copy;
1510         $old_hold->clear_prev_check_time;
1511         $editor->update_action_hold_request($old_hold) 
1512             or return (undef, $editor->event);
1513         $retarget = 1;
1514         }
1515
1516         return ($best_hold, undef, $retarget);
1517 }
1518
1519
1520
1521
1522
1523
1524 __PACKAGE__->register_method(
1525         method => 'all_rec_holds',
1526         api_name => 'open-ils.circ.holds.retrieve_all_from_title',
1527 );
1528
1529 sub all_rec_holds {
1530         my( $self, $conn, $auth, $title_id, $args ) = @_;
1531
1532         my $e = new_editor(authtoken=>$auth);
1533         $e->checkauth or return $e->event;
1534         $e->allowed('VIEW_HOLD') or return $e->event;
1535
1536         $args ||= { fulfillment_time => undef };
1537         $args->{cancel_time} = undef;
1538
1539         my $resp = { volume_holds => [], copy_holds => [] };
1540
1541         $resp->{title_holds} = $e->search_action_hold_request(
1542                 { 
1543                         hold_type => OILS_HOLD_TYPE_TITLE, 
1544                         target => $title_id, 
1545                         %$args 
1546                 }, {idlist=>1} );
1547
1548         my $vols = $e->search_asset_call_number(
1549                 { record => $title_id, deleted => 'f' }, {idlist=>1});
1550
1551         return $resp unless @$vols;
1552
1553         $resp->{volume_holds} = $e->search_action_hold_request(
1554                 { 
1555                         hold_type => OILS_HOLD_TYPE_VOLUME, 
1556                         target => $vols,
1557                         %$args }, 
1558                 {idlist=>1} );
1559
1560         my $copies = $e->search_asset_copy(
1561                 { call_number => $vols, deleted => 'f' }, {idlist=>1});
1562
1563         return $resp unless @$copies;
1564
1565         $resp->{copy_holds} = $e->search_action_hold_request(
1566                 { 
1567                         hold_type => OILS_HOLD_TYPE_COPY,
1568                         target => $copies,
1569                         %$args }, 
1570                 {idlist=>1} );
1571
1572         return $resp;
1573 }
1574
1575
1576
1577
1578
1579 __PACKAGE__->register_method(
1580         method => 'uber_hold',
1581     authoritative => 1,
1582         api_name => 'open-ils.circ.hold.details.retrieve'
1583 );
1584
1585 sub uber_hold {
1586         my($self, $client, $auth, $hold_id) = @_;
1587         my $e = new_editor(authtoken=>$auth);
1588         $e->checkauth or return $e->event;
1589         $e->allowed('VIEW_HOLD') or return $e->event;
1590
1591         my $resp = {};
1592
1593         my $hold = $e->retrieve_action_hold_request(
1594                 [
1595                         $hold_id,
1596                         {
1597                                 flesh => 1,
1598                                 flesh_fields => { ahr => [ 'current_copy', 'usr' ] }
1599                         }
1600                 ]
1601         ) or return $e->event;
1602
1603         my $user = $hold->usr;
1604         $hold->usr($user->id);
1605
1606         my $card = $e->retrieve_actor_card($user->card)
1607                 or return $e->event;
1608
1609         my( $mvr, $volume, $copy ) = find_hold_mvr($e, $hold);
1610
1611         flesh_hold_notices([$hold], $e);
1612         flesh_hold_transits([$hold]);
1613
1614         return {
1615                 hold            => $hold,
1616                 copy            => $copy,
1617                 volume  => $volume,
1618                 mvr             => $mvr,
1619                 status  => _hold_status($e, $hold),
1620                 patron_first => $user->first_given_name,
1621                 patron_last  => $user->family_name,
1622                 patron_barcode => $card->barcode,
1623         };
1624 }
1625
1626
1627
1628 # -----------------------------------------------------
1629 # Returns the MVR object that represents what the
1630 # hold is all about
1631 # -----------------------------------------------------
1632 sub find_hold_mvr {
1633         my( $e, $hold ) = @_;
1634
1635         my $tid;
1636         my $copy;
1637         my $volume;
1638
1639         if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
1640                 my $mr = $e->retrieve_metabib_metarecord($hold->target)
1641                         or return $e->event;
1642                 $tid = $mr->master_record;
1643
1644         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
1645                 $tid = $hold->target;
1646
1647         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
1648                 $volume = $e->retrieve_asset_call_number($hold->target)
1649                         or return $e->event;
1650                 $tid = $volume->record;
1651
1652         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_COPY ) {
1653                 $copy = $e->retrieve_asset_copy($hold->target)
1654                         or return $e->event;
1655                 $volume = $e->retrieve_asset_call_number($copy->call_number)
1656                         or return $e->event;
1657                 $tid = $volume->record;
1658         }
1659
1660         if(!$copy and ref $hold->current_copy ) {
1661                 $copy = $hold->current_copy;
1662                 $hold->current_copy($copy->id);
1663         }
1664
1665         if(!$volume and $copy) {
1666                 $volume = $e->retrieve_asset_call_number($copy->call_number);
1667         }
1668
1669         my $title = $e->retrieve_biblio_record_entry($tid);
1670         return ( $U->record_to_mvr($title), $volume, $copy );
1671 }
1672
1673
1674
1675
1676 1;