]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ/Holds.pm
allow the pickup lib on a hold to be altered (and subsequently put item into transit...
[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     # --------------------------------------------------------------
546     # if the hold is on the holds shelf and the pickup lib changes, 
547     # we need to create a new transit
548     # --------------------------------------------------------------
549     if( ($orig_hold->pickup_lib ne $hold->pickup_lib) and (_hold_status($e, $hold) == 4)) {
550         return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
551         return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
552         my $evt = transit_hold($e, $orig_hold, $hold, 
553             $e->retrieve_asset_copy($hold->current_copy));
554         return $evt if $evt;
555     }
556
557     update_hold_if_frozen($self, $e, $hold, $orig_hold);
558     $e->update_action_hold_request($hold) or return $e->die_event;
559     $e->commit;
560     return $hold->id;
561 }
562
563 sub transit_hold {
564     my($e, $orig_hold, $hold, $copy) = @_;
565     my $src = $orig_hold->pickup_lib;
566     my $dest = $hold->pickup_lib;
567
568     $logger->info("putting hold into transit on pickup_lib update");
569
570     my $transit = Fieldmapper::action::transit_copy->new;
571     $transit->source($src);
572     $transit->dest($dest);
573     $transit->target_copy($copy->id);
574     $transit->source_send_time('now');
575     $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
576
577     $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
578     $copy->editor($e->requestor->id);
579     $copy->edit_date('now');
580
581     $e->create_action_transit_copy($transit) or return $e->die_event;
582     $e->update_asset_copy($copy) or return $e->die_event;
583     return undef;
584 }
585
586 # if the hold is frozen, this method ensures that the hold is not "targeted", 
587 # that is, it clears the current_copy and prev_check_time to essentiallly 
588 # reset the hold.  If it is being activated, it runs the targeter in the background
589 sub update_hold_if_frozen {
590     my($self, $e, $hold, $orig_hold) = @_;
591     return if $hold->capture_time;
592
593     if($U->is_true($hold->frozen)) {
594         $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
595         $hold->clear_current_copy;
596         $hold->clear_prev_check_time;
597
598     } else {
599         if($U->is_true($orig_hold->frozen)) {
600             $logger->info("Running targeter on activated hold ".$hold->id);
601                 $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
602         }
603     }
604 }
605
606
607 __PACKAGE__->register_method(
608         method  => "retrieve_hold_status",
609         api_name        => "open-ils.circ.hold.status.retrieve",
610         notes           => <<"  NOTE");
611         Calculates the current status of the hold.
612         the requestor must have VIEW_HOLD permissions if the hold is for a user
613         other than the requestor.
614         Returns -1  on error (for now)
615         Returns 1 for 'waiting for copy to become available'
616         Returns 2 for 'waiting for copy capture'
617         Returns 3 for 'in transit'
618         Returns 4 for 'arrived'
619         NOTE
620
621 sub retrieve_hold_status {
622         my($self, $client, $auth, $hold_id) = @_;
623
624         my $e = new_editor(authtoken => $auth);
625         return $e->event unless $e->checkauth;
626         my $hold = $e->retrieve_action_hold_request($hold_id)
627                 or return $e->event;
628
629         if( $e->requestor->id != $hold->usr ) {
630                 return $e->event unless $e->allowed('VIEW_HOLD');
631         }
632
633         return _hold_status($e, $hold);
634
635 }
636
637 sub _hold_status {
638         my($e, $hold) = @_;
639         return 1 unless $hold->current_copy;
640         return 2 unless $hold->capture_time;
641
642         my $copy = $hold->current_copy;
643         unless( ref $copy ) {
644                 $copy = $e->retrieve_asset_copy($hold->current_copy)
645                         or return $e->event;
646         }
647
648         return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
649         return 4 if $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF;
650
651         return -1;
652 }
653
654
655 #sub find_local_hold {
656 #       my( $class, $session, $copy, $user ) = @_;
657 #       return $class->find_nearest_permitted_hold($session, $copy, $user);
658 #}
659
660
661 sub fetch_open_hold_by_current_copy {
662         my $class = shift;
663         my $copyid = shift;
664         my $hold = $apputils->simplereq(
665                 'open-ils.cstore', 
666                 'open-ils.cstore.direct.action.hold_request.search.atomic',
667                 { current_copy =>  $copyid , cancel_time => undef, fulfillment_time => undef });
668         return $hold->[0] if ref($hold);
669         return undef;
670 }
671
672 sub fetch_related_holds {
673         my $class = shift;
674         my $copyid = shift;
675         return $apputils->simplereq(
676                 'open-ils.cstore', 
677                 'open-ils.cstore.direct.action.hold_request.search.atomic',
678                 { current_copy =>  $copyid , cancel_time => undef, fulfillment_time => undef });
679 }
680
681
682 __PACKAGE__->register_method (
683         method          => "hold_pull_list",
684         api_name                => "open-ils.circ.hold_pull_list.retrieve",
685         signature       => q/
686                 Returns a list of holds that need to be "pulled"
687                 by a given location
688         /
689 );
690
691 __PACKAGE__->register_method (
692         method          => "hold_pull_list",
693         api_name                => "open-ils.circ.hold_pull_list.id_list.retrieve",
694         signature       => q/
695                 Returns a list of hold ID's that need to be "pulled"
696                 by a given location
697         /
698 );
699
700
701 sub hold_pull_list {
702         my( $self, $conn, $authtoken, $limit, $offset ) = @_;
703         my( $reqr, $evt ) = $U->checkses($authtoken);
704         return $evt if $evt;
705
706         my $org = $reqr->ws_ou || $reqr->home_ou;
707         # the perm locaiton shouldn't really matter here since holds
708         # will exist all over and VIEW_HOLDS should be universal
709         $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
710         return $evt if $evt;
711
712         if( $self->api_name =~ /id_list/ ) {
713                 return $U->storagereq(
714                         'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.atomic',
715                         $org, $limit, $offset ); 
716         } else {
717                 return $U->storagereq(
718                         'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.atomic',
719                         $org, $limit, $offset ); 
720         }
721 }
722
723 __PACKAGE__->register_method (
724         method          => 'fetch_hold_notify',
725         api_name                => 'open-ils.circ.hold_notification.retrieve_by_hold',
726         signature       => q/ 
727                 Returns a list of hold notification objects based on hold id.
728                 @param authtoken The loggin session key
729                 @param holdid The id of the hold whose notifications we want to retrieve
730                 @return An array of hold notification objects, event on error.
731         /
732 );
733
734 sub fetch_hold_notify {
735         my( $self, $conn, $authtoken, $holdid ) = @_;
736         my( $requestor, $evt ) = $U->checkses($authtoken);
737         return $evt if $evt;
738         my ($hold, $patron);
739         ($hold, $evt) = $U->fetch_hold($holdid);
740         return $evt if $evt;
741         ($patron, $evt) = $U->fetch_user($hold->usr);
742         return $evt if $evt;
743
744         $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
745         return $evt if $evt;
746
747         $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
748         return $U->cstorereq(
749                 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
750 }
751
752
753 __PACKAGE__->register_method (
754         method          => 'create_hold_notify',
755         api_name                => 'open-ils.circ.hold_notification.create',
756         signature       => q/
757                 Creates a new hold notification object
758                 @param authtoken The login session key
759                 @param notification The hold notification object to create
760                 @return ID of the new object on success, Event on error
761                 /
762 );
763 =head old
764 sub __create_hold_notify {
765         my( $self, $conn, $authtoken, $notification ) = @_;
766         my( $requestor, $evt ) = $U->checkses($authtoken);
767         return $evt if $evt;
768         my ($hold, $patron);
769         ($hold, $evt) = $U->fetch_hold($notification->hold);
770         return $evt if $evt;
771         ($patron, $evt) = $U->fetch_user($hold->usr);
772         return $evt if $evt;
773
774         # XXX perm depth probably doesn't matter here -- should always be consortium level
775         $evt = $U->check_perms($requestor->id, $patron->home_ou, 'CREATE_HOLD_NOTIFICATION');
776         return $evt if $evt;
777
778         # Set the proper notifier 
779         $notification->notify_staff($requestor->id);
780         my $id = $U->storagereq(
781                 'open-ils.storage.direct.action.hold_notification.create', $notification );
782         return $U->DB_UPDATE_FAILED($notification) unless $id;
783         $logger->info("User ".$requestor->id." successfully created new hold notification $id");
784         return $id;
785 }
786 =cut
787
788 sub create_hold_notify {
789    my( $self, $conn, $auth, $note ) = @_;
790    my $e = new_editor(authtoken=>$auth, xact=>1);
791    return $e->die_event unless $e->checkauth;
792
793    my $hold = $e->retrieve_action_hold_request($note->hold)
794       or return $e->die_event;
795    my $patron = $e->retrieve_actor_user($hold->usr) 
796       or return $e->die_event;
797
798    return $e->die_event unless 
799       $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
800
801         $note->notify_staff($e->requestor->id);
802    $e->create_action_hold_notification($note) or return $e->die_event;
803    $e->commit;
804    return $note->id;
805 }
806
807
808 __PACKAGE__->register_method(
809         method  => 'reset_hold',
810         api_name        => 'open-ils.circ.hold.reset',
811         signature       => q/
812                 Un-captures and un-targets a hold, essentially returning
813                 it to the state it was in directly after it was placed,
814                 then attempts to re-target the hold
815                 @param authtoken The login session key
816                 @param holdid The id of the hold
817         /
818 );
819
820
821 sub reset_hold {
822         my( $self, $conn, $auth, $holdid ) = @_;
823         my $reqr;
824         my ($hold, $evt) = $U->fetch_hold($holdid);
825         return $evt if $evt;
826         ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD'); # XXX stronger permission
827         return $evt if $evt;
828         $evt = _reset_hold($self, $reqr, $hold);
829         return $evt if $evt;
830         return 1;
831 }
832
833 sub _reset_hold {
834         my ($self, $reqr, $hold) = @_;
835
836         my $e = new_editor(xact =>1, requestor => $reqr);
837
838         $logger->info("reseting hold ".$hold->id);
839
840         my $hid = $hold->id;
841
842         if( $hold->capture_time and $hold->current_copy ) {
843
844                 my $copy = $e->retrieve_asset_copy($hold->current_copy)
845                         or return $e->event;
846
847                 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
848                         $logger->info("setting copy to status 'reshelving' on hold retarget");
849                         $copy->status(OILS_COPY_STATUS_RESHELVING);
850                         $copy->editor($e->requestor->id);
851                         $copy->edit_date('now');
852                         $e->update_asset_copy($copy) or return $e->event;
853
854                 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
855
856                         # We don't want the copy to remain "in transit"
857                         $copy->status(OILS_COPY_STATUS_RESHELVING);
858                         $logger->warn("! reseting hold [$hid] that is in transit");
859                         my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
860
861                         if( $transid ) {
862                                 my $trans = $e->retrieve_action_transit_copy($transid);
863                                 if( $trans ) {
864                                         $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
865                                         my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1);
866                                         $logger->info("Transit abort completed with result $evt");
867                                         return $evt unless "$evt" eq 1;
868                                 }
869                         }
870                 }
871         }
872
873         $hold->clear_capture_time;
874         $hold->clear_current_copy;
875
876         $e->update_action_hold_request($hold) or return $e->event;
877         $e->commit;
878
879         $U->storagereq(
880                 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
881
882         return undef;
883 }
884
885
886 __PACKAGE__->register_method(
887         method => 'fetch_open_title_holds',
888         api_name        => 'open-ils.circ.open_holds.retrieve',
889         signature       => q/
890                 Returns a list ids of un-fulfilled holds for a given title id
891                 @param authtoken The login session key
892                 @param id the id of the item whose holds we want to retrieve
893                 @param type The hold type - M, T, V, C
894         /
895 );
896
897 sub fetch_open_title_holds {
898         my( $self, $conn, $auth, $id, $type, $org ) = @_;
899         my $e = new_editor( authtoken => $auth );
900         return $e->event unless $e->checkauth;
901
902         $type ||= "T";
903         $org ||= $e->requestor->ws_ou;
904
905 #       return $e->search_action_hold_request(
906 #               { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
907
908         # XXX make me return IDs in the future ^--
909         my $holds = $e->search_action_hold_request(
910                 { 
911                         target                          => $id, 
912                         cancel_time                     => undef, 
913                         hold_type                       => $type, 
914                         fulfillment_time        => undef 
915                 }
916         );
917
918         flesh_hold_transits($holds);
919         return $holds;
920 }
921
922
923 sub flesh_hold_transits {
924         my $holds = shift;
925         for my $hold ( @$holds ) {
926                 $hold->transit(
927                         $apputils->simplereq(
928                                 'open-ils.cstore',
929                                 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
930                                 { hold => $hold->id },
931                                 { order_by => { ahtc => 'id desc' }, limit => 1 }
932                         )->[0]
933                 );
934         }
935 }
936
937 sub flesh_hold_notices {
938         my( $holds, $e ) = @_;
939         $e ||= new_editor();
940
941         for my $hold (@$holds) {
942                 my $notices = $e->search_action_hold_notification(
943                         [
944                                 { hold => $hold->id },
945                                 { order_by => { anh => 'notify_time desc' } },
946                         ],
947                         {idlist=>1}
948                 );
949
950                 $hold->notify_count(scalar(@$notices));
951                 if( @$notices ) {
952                         my $n = $e->retrieve_action_hold_notification($$notices[0])
953                                 or return $e->event;
954                         $hold->notify_time($n->notify_time);
955                 }
956         }
957 }
958
959
960
961
962 __PACKAGE__->register_method(
963         method => 'fetch_captured_holds',
964         api_name        => 'open-ils.circ.captured_holds.on_shelf.retrieve',
965         signature       => q/
966                 Returns a list of un-fulfilled holds for a given title id
967                 @param authtoken The login session key
968                 @param org The org id of the location in question
969         /
970 );
971
972 __PACKAGE__->register_method(
973         method => 'fetch_captured_holds',
974         api_name        => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
975         signature       => q/
976                 Returns a list ids of un-fulfilled holds for a given title id
977                 @param authtoken The login session key
978                 @param org The org id of the location in question
979         /
980 );
981
982 sub fetch_captured_holds {
983         my( $self, $conn, $auth, $org ) = @_;
984
985         my $e = new_editor(authtoken => $auth);
986         return $e->event unless $e->checkauth;
987         return $e->event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
988
989         $org ||= $e->requestor->ws_ou;
990
991         my $holds = $e->search_action_hold_request(
992                 { 
993                         capture_time            => { "!=" => undef },
994                         current_copy            => { "!=" => undef },
995                         fulfillment_time        => undef,
996                         pickup_lib                      => $org,
997                         cancel_time                     => undef,
998                 }
999         );
1000
1001         my @res;
1002         for my $h (@$holds) {
1003                 my $copy = $e->retrieve_asset_copy($h->current_copy)
1004                         or return $e->event;
1005                 push( @res, $h ) if 
1006                         $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF;
1007         }
1008
1009         if( ! $self->api_name =~ /id_list/ ) {
1010                 flesh_hold_transits(\@res);
1011                 flesh_hold_notices(\@res, $e);
1012         }
1013
1014         if( $self->api_name =~ /id_list/ ) {
1015                 return [ map { $_->id } @res ];
1016         } else {
1017                 return \@res;
1018         }
1019 }
1020
1021 __PACKAGE__->register_method(
1022         method  => "check_title_hold",
1023         api_name        => "open-ils.circ.title_hold.is_possible",
1024         notes           => q/
1025                 Determines if a hold were to be placed by a given user,
1026                 whether or not said hold would have any potential copies
1027                 to fulfill it.
1028                 @param authtoken The login session key
1029                 @param params A hash of named params including:
1030                         patronid  - the id of the hold recipient
1031                         titleid (brn) - the id of the title to be held
1032                         depth   - the hold range depth (defaults to 0)
1033         /);
1034
1035 sub check_title_hold {
1036         my( $self, $client, $authtoken, $params ) = @_;
1037
1038         my %params              = %$params;
1039         my $titleid             = $params{titleid} ||"";
1040         my $volid               = $params{volume_id};
1041         my $copyid              = $params{copy_id};
1042         my $mrid                = $params{mrid} ||"";
1043         my $depth               = $params{depth} || 0;
1044         my $pickup_lib  = $params{pickup_lib};
1045         my $hold_type   = $params{hold_type} || 'T';
1046     my $selection_ou = $params{selection_ou} || $pickup_lib;
1047
1048         my $e = new_editor(authtoken=>$authtoken);
1049         return $e->event unless $e->checkauth;
1050         my $patron = $e->retrieve_actor_user($params{patronid})
1051                 or return $e->event;
1052
1053         if( $e->requestor->id ne $patron->id ) {
1054                 return $e->event unless 
1055                         $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
1056         }
1057
1058         return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
1059
1060         my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
1061                 or return $e->event;
1062
1063     my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
1064     my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
1065
1066     if(defined $soft_boundary and $$params{depth} < $soft_boundary) {
1067         # work up the tree and as soon as we find a potential copy, use that depth
1068         # also, make sure we don't go past the hard boundary if it exists
1069
1070         # our min boundary is the greater of user-specified boundary or hard boundary
1071         my $min_depth = (defined $hard_boundary and $hard_boundary > $$params{depth}) ?  
1072             $hard_boundary : $$params{depth};
1073
1074         my $depth = $soft_boundary;
1075         while($depth >= $min_depth) {
1076             $logger->info("performing hold possibility check with soft boundary $depth");
1077             return {success => 1, depth => $depth}
1078                 if do_possibility_checks($e, $patron, $request_lib, $depth, %params);
1079             $depth--;
1080         }
1081         return {success => 0};
1082
1083     } elsif(defined $hard_boundary and $$params{depth} < $hard_boundary) {
1084         # there is no soft boundary, enforce the hard boundary if it exists
1085         $logger->info("performing hold possibility check with hard boundary $hard_boundary");
1086         if(do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params)) {
1087             return {success => 1, depth => $hard_boundary}
1088         } else {
1089             return {success => 0};
1090         }
1091
1092     } else {
1093         # no boundaries defined, fall back to user specifed boundary or no boundary
1094         $logger->info("performing hold possibility check with no boundary");
1095         if(do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params)) {
1096             return {success => 1, depth => $hard_boundary};
1097         } else {
1098             return {success => 0};
1099         }
1100     }
1101 }
1102
1103 sub do_possibility_checks {
1104     my($e, $patron, $request_lib, $depth, %params) = @_;
1105
1106         my $titleid             = $params{titleid} ||"";
1107         my $volid               = $params{volume_id};
1108         my $copyid              = $params{copy_id};
1109         my $mrid                = $params{mrid} ||"";
1110         my $pickup_lib  = $params{pickup_lib};
1111         my $hold_type   = $params{hold_type} || 'T';
1112     my $selection_ou = $params{selection_ou} || $pickup_lib;
1113
1114
1115         my $copy;
1116         my $volume;
1117         my $title;
1118
1119         if( $hold_type eq OILS_HOLD_TYPE_COPY ) {
1120
1121                 $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
1122                 $volume = $e->retrieve_asset_call_number($copy->call_number)
1123                         or return $e->event;
1124                 $title = $e->retrieve_biblio_record_entry($volume->record)
1125                         or return $e->event;
1126                 return verify_copy_for_hold( 
1127                         $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib );
1128
1129         } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
1130
1131                 $volume = $e->retrieve_asset_call_number($volid)
1132                         or return $e->event;
1133                 $title = $e->retrieve_biblio_record_entry($volume->record)
1134                         or return $e->event;
1135
1136                 return _check_volume_hold_is_possible(
1137                         $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou);
1138
1139         } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
1140
1141                 return _check_title_hold_is_possible(
1142                         $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou);
1143
1144         } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
1145
1146                 my $maps = $e->search_metabib_source_map({metarecord=>$mrid});
1147                 my @recs = map { $_->source } @$maps;
1148                 for my $rec (@recs) {
1149                         return 1 if (_check_title_hold_is_possible(
1150                                 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou));
1151                 }
1152                 return 0;       
1153         }
1154 }
1155
1156 my %prox_cache;
1157
1158 sub _check_metarecord_hold_is_possible {
1159         my( $mrid, $rangelib, $depth, $request_lib, $patron, $requestor, $pickup_lib ) = @_;
1160    
1161    my $e = new_editor();
1162
1163     # this monster will grab the id and circ_lib of all of the "holdable" copies for the given metarecord
1164     my $copies = $e->json_query(
1165         { 
1166             select => { acp => ['id', 'circ_lib'] },
1167             from => {
1168                 acp => {
1169                     acn => {
1170                         field => 'id',
1171                         fkey => 'call_number',
1172                         'join' => {
1173                             mmrsm => {
1174                                 field => 'source',
1175                                 fkey => 'record',
1176                                 filter => { metarecord => $mrid }
1177                             }
1178                         }
1179                     },
1180                     acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
1181                     ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
1182                 }
1183             }, 
1184             where => {
1185                 '+acp' => { circulate => 't', deleted => 'f', holdable => 't' }
1186             }
1187         }
1188     );
1189
1190    return $e->event unless defined $copies;
1191    $logger->info("metarecord possible found ".scalar(@$copies)." potential copies");
1192    return 0 unless @$copies;
1193
1194    # -----------------------------------------------------------------------
1195    # sort the copies into buckets based on their circ_lib proximity to 
1196    # the patron's home_ou.  
1197    # -----------------------------------------------------------------------
1198
1199    my $home_org = $patron->home_ou;
1200    my $req_org = $request_lib->id;
1201
1202     $prox_cache{$home_org} = 
1203         $e->search_actor_org_unit_proximity({from_org => $home_org})
1204         unless $prox_cache{$home_org};
1205     my $home_prox = $prox_cache{$home_org};
1206
1207    my %buckets;
1208    my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
1209    push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1210
1211    my @keys = sort { $a <=> $b } keys %buckets;
1212
1213
1214    if( $home_org ne $req_org ) {
1215       # -----------------------------------------------------------------------
1216       # shove the copies close to the request_lib into the primary buckets 
1217       # directly before the farthest away copies.  That way, they are not 
1218       # given priority, but they are checked before the farthest copies.
1219       # -----------------------------------------------------------------------
1220
1221         $prox_cache{$req_org} = 
1222             $e->search_actor_org_unit_proximity({from_org => $req_org})
1223             unless $prox_cache{$req_org};
1224         my $req_prox = $prox_cache{$req_org};
1225
1226       my %buckets2;
1227       my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
1228       push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1229
1230       my $highest_key = $keys[@keys - 1];  # the farthest prox in the exising buckets
1231       my $new_key = $highest_key - 0.5; # right before the farthest prox
1232       my @keys2 = sort { $a <=> $b } keys %buckets2;
1233       for my $key (@keys2) {
1234          last if $key >= $highest_key;
1235          push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
1236       }
1237    }
1238
1239    @keys = sort { $a <=> $b } keys %buckets;
1240
1241    my %seen;
1242    for my $key (@keys) {
1243       my @cps = @{$buckets{$key}};
1244
1245       $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
1246
1247       for my $copyid (@cps) {
1248
1249          next if $seen{$copyid};
1250          $seen{$copyid} = 1; # there could be dupes given the merged buckets
1251          my $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
1252          $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
1253
1254          my $vol = $e->retrieve_asset_call_number(
1255            [ $copy->call_number, { flesh => 1, flesh_fields => { acn => ['record'] } } ] );
1256
1257          return 1 if verify_copy_for_hold( 
1258             $patron, $requestor, $vol->record, $copy, $pickup_lib, $request_lib );
1259    
1260       }
1261    }
1262
1263    return 0;
1264 }
1265
1266 sub create_ranged_org_filter {
1267     my($e, $selection_ou, $depth) = @_;
1268
1269     # find the orgs from which this hold may be fulfilled, 
1270     # based on the selection_ou and depth
1271
1272     my $top_org = $e->search_actor_org_unit([
1273         {parent_ou => undef}, 
1274         {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
1275     my %org_filter;
1276
1277     return () if $depth == $top_org->ou_type->depth;
1278
1279     my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
1280     %org_filter = (circ_lib => []);
1281     push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
1282
1283     $logger->info("hold org filter at depth $depth and selection_ou ".
1284         "$selection_ou created list of @{$org_filter{circ_lib}}");
1285
1286     return %org_filter;
1287 }
1288
1289
1290 sub _check_title_hold_is_possible {
1291         my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
1292    
1293     my $e = new_editor();
1294     my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
1295
1296     # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
1297     my $copies = $e->json_query(
1298         { 
1299             select => { acp => ['id', 'circ_lib'] },
1300             from => {
1301                 acp => {
1302                     acn => {
1303                         field => 'id',
1304                         fkey => 'call_number',
1305                         'join' => {
1306                             bre => {
1307                                 field => 'id',
1308                                 filter => { id => $titleid },
1309                                 fkey => 'record'
1310                             }
1311                         }
1312                     },
1313                     acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
1314                     ccs => { field => 'id', filter => { holdable => 't'}, fkey => 'status' }
1315                 }
1316             }, 
1317             where => {
1318                 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
1319             }
1320         }
1321     );
1322
1323    return $e->event unless defined $copies;
1324    $logger->info("title possible found ".scalar(@$copies)." potential copies");
1325    return 0 unless @$copies;
1326
1327    # -----------------------------------------------------------------------
1328    # sort the copies into buckets based on their circ_lib proximity to 
1329    # the patron's home_ou.  
1330    # -----------------------------------------------------------------------
1331
1332    my $home_org = $patron->home_ou;
1333    my $req_org = $request_lib->id;
1334
1335     $logger->info("prox cache $home_org " . $prox_cache{$home_org});
1336
1337     $prox_cache{$home_org} = 
1338         $e->search_actor_org_unit_proximity({from_org => $home_org})
1339         unless $prox_cache{$home_org};
1340     my $home_prox = $prox_cache{$home_org};
1341
1342    my %buckets;
1343    my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
1344    push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1345
1346    my @keys = sort { $a <=> $b } keys %buckets;
1347
1348
1349    if( $home_org ne $req_org ) {
1350       # -----------------------------------------------------------------------
1351       # shove the copies close to the request_lib into the primary buckets 
1352       # directly before the farthest away copies.  That way, they are not 
1353       # given priority, but they are checked before the farthest copies.
1354       # -----------------------------------------------------------------------
1355         $prox_cache{$req_org} = 
1356             $e->search_actor_org_unit_proximity({from_org => $req_org})
1357             unless $prox_cache{$req_org};
1358         my $req_prox = $prox_cache{$req_org};
1359
1360
1361       my %buckets2;
1362       my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
1363       push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1364
1365       my $highest_key = $keys[@keys - 1];  # the farthest prox in the exising buckets
1366       my $new_key = $highest_key - 0.5; # right before the farthest prox
1367       my @keys2 = sort { $a <=> $b } keys %buckets2;
1368       for my $key (@keys2) {
1369          last if $key >= $highest_key;
1370          push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
1371       }
1372    }
1373
1374    @keys = sort { $a <=> $b } keys %buckets;
1375
1376    my $title;
1377    my %seen;
1378    for my $key (@keys) {
1379       my @cps = @{$buckets{$key}};
1380
1381       $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
1382
1383       for my $copyid (@cps) {
1384
1385          next if $seen{$copyid};
1386          $seen{$copyid} = 1; # there could be dupes given the merged buckets
1387          my $copy = $e->retrieve_asset_copy($copyid) or return $e->event;
1388          $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
1389
1390          unless($title) { # grab the title if we don't already have it
1391             my $vol = $e->retrieve_asset_call_number(
1392                [ $copy->call_number, { flesh => 1, flesh_fields => { acn => ['record'] } } ] );
1393             $title = $vol->record;
1394          }
1395    
1396          return 1 if verify_copy_for_hold( 
1397             $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
1398    
1399       }
1400    }
1401
1402    return 0;
1403 }
1404
1405
1406 sub _check_volume_hold_is_possible {
1407         my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
1408     my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
1409         my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
1410         $logger->info("checking possibility of volume hold for volume ".$vol->id);
1411         for my $copy ( @$copies ) {
1412                 return 1 if verify_copy_for_hold( 
1413                         $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
1414         }
1415         return 0;
1416 }
1417
1418
1419
1420 sub verify_copy_for_hold {
1421         my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib ) = @_;
1422         $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
1423         return 1 if OpenILS::Utils::PermitHold::permit_copy_hold(
1424                 {       patron                          => $patron, 
1425                         requestor                       => $requestor, 
1426                         copy                            => $copy,
1427                         title                           => $title, 
1428                         title_descriptor        => $title->fixed_fields, # this is fleshed into the title object
1429                         pickup_lib                      => $pickup_lib,
1430                         request_lib                     => $request_lib,
1431             new_hold            => 1
1432                 } 
1433         );
1434         return 0;
1435 }
1436
1437
1438
1439 sub find_nearest_permitted_hold {
1440
1441         my $class       = shift;
1442         my $editor      = shift; # CStoreEditor object
1443         my $copy                = shift; # copy to target
1444         my $user                = shift; # staff 
1445         my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
1446         my $evt         = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
1447
1448         my $bc = $copy->barcode;
1449
1450         # find any existing holds that already target this copy
1451         my $old_holds = $editor->search_action_hold_request(
1452                 {       current_copy => $copy->id, 
1453                         cancel_time => undef, 
1454                         capture_time => undef 
1455                 } 
1456         );
1457
1458         # hold->type "R" means we need this copy
1459         for my $h (@$old_holds) { return ($h) if $h->hold_type eq 'R'; }
1460
1461
1462     my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
1463
1464         $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
1465         " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
1466
1467         # search for what should be the best holds for this copy to fulfill
1468         my $best_holds = $U->storagereq(
1469                 "open-ils.storage.action.hold_request.nearest_hold.atomic",
1470                 $user->ws_ou, $copy->id, 10, $hold_stall_interval );
1471
1472         unless(@$best_holds) {
1473
1474                 if( my $hold = $$old_holds[0] ) {
1475                         $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
1476                         return ($hold);
1477                 }
1478
1479                 $logger->info("circulator: no suitable holds found for copy $bc");
1480                 return (undef, $evt);
1481         }
1482
1483
1484         my $best_hold;
1485
1486         # for each potential hold, we have to run the permit script
1487         # to make sure the hold is actually permitted.
1488         for my $holdid (@$best_holds) {
1489                 next unless $holdid;
1490                 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
1491
1492                 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
1493                 my $reqr = $editor->retrieve_actor_user($hold->requestor) or next;
1494                 my $rlib = $editor->retrieve_actor_org_unit($hold->request_lib) or next;
1495
1496                 # see if this hold is permitted
1497                 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
1498                         {       patron_id                       => $hold->usr,
1499                                 requestor                       => $reqr,
1500                                 copy                            => $copy,
1501                                 pickup_lib                      => $hold->pickup_lib,
1502                                 request_lib                     => $rlib,
1503                         } 
1504                 );
1505
1506                 if( $permitted ) {
1507                         $best_hold = $hold;
1508                         last;
1509                 }
1510         }
1511
1512
1513         unless( $best_hold ) { # no "good" permitted holds were found
1514                 if( my $hold = $$old_holds[0] ) { # can we return a pre-targeted hold?
1515                         $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
1516                         return ($hold);
1517                 }
1518
1519                 # we got nuthin
1520                 $logger->info("circulator: no suitable holds found for copy $bc");
1521                 return (undef, $evt);
1522         }
1523
1524         $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
1525
1526         # indicate a permitted hold was found
1527         return $best_hold if $check_only;
1528
1529         # we've found a permitted hold.  we need to "grab" the copy 
1530         # to prevent re-targeted holds (next part) from re-grabbing the copy
1531         $best_hold->current_copy($copy->id);
1532         $editor->update_action_hold_request($best_hold) 
1533                 or return (undef, $editor->event);
1534
1535
1536     my $retarget = 0;
1537
1538         # re-target any other holds that already target this copy
1539         for my $old_hold (@$old_holds) {
1540                 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
1541                 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
1542             $old_hold->id." after a better hold [".$best_hold->id."] was found");
1543         $old_hold->clear_current_copy;
1544         $old_hold->clear_prev_check_time;
1545         $editor->update_action_hold_request($old_hold) 
1546             or return (undef, $editor->event);
1547         $retarget = 1;
1548         }
1549
1550         return ($best_hold, undef, $retarget);
1551 }
1552
1553
1554
1555
1556
1557
1558 __PACKAGE__->register_method(
1559         method => 'all_rec_holds',
1560         api_name => 'open-ils.circ.holds.retrieve_all_from_title',
1561 );
1562
1563 sub all_rec_holds {
1564         my( $self, $conn, $auth, $title_id, $args ) = @_;
1565
1566         my $e = new_editor(authtoken=>$auth);
1567         $e->checkauth or return $e->event;
1568         $e->allowed('VIEW_HOLD') or return $e->event;
1569
1570         $args ||= { fulfillment_time => undef };
1571         $args->{cancel_time} = undef;
1572
1573         my $resp = { volume_holds => [], copy_holds => [] };
1574
1575         $resp->{title_holds} = $e->search_action_hold_request(
1576                 { 
1577                         hold_type => OILS_HOLD_TYPE_TITLE, 
1578                         target => $title_id, 
1579                         %$args 
1580                 }, {idlist=>1} );
1581
1582         my $vols = $e->search_asset_call_number(
1583                 { record => $title_id, deleted => 'f' }, {idlist=>1});
1584
1585         return $resp unless @$vols;
1586
1587         $resp->{volume_holds} = $e->search_action_hold_request(
1588                 { 
1589                         hold_type => OILS_HOLD_TYPE_VOLUME, 
1590                         target => $vols,
1591                         %$args }, 
1592                 {idlist=>1} );
1593
1594         my $copies = $e->search_asset_copy(
1595                 { call_number => $vols, deleted => 'f' }, {idlist=>1});
1596
1597         return $resp unless @$copies;
1598
1599         $resp->{copy_holds} = $e->search_action_hold_request(
1600                 { 
1601                         hold_type => OILS_HOLD_TYPE_COPY,
1602                         target => $copies,
1603                         %$args }, 
1604                 {idlist=>1} );
1605
1606         return $resp;
1607 }
1608
1609
1610
1611
1612
1613 __PACKAGE__->register_method(
1614         method => 'uber_hold',
1615     authoritative => 1,
1616         api_name => 'open-ils.circ.hold.details.retrieve'
1617 );
1618
1619 sub uber_hold {
1620         my($self, $client, $auth, $hold_id) = @_;
1621         my $e = new_editor(authtoken=>$auth);
1622         $e->checkauth or return $e->event;
1623         $e->allowed('VIEW_HOLD') or return $e->event;
1624
1625         my $resp = {};
1626
1627         my $hold = $e->retrieve_action_hold_request(
1628                 [
1629                         $hold_id,
1630                         {
1631                                 flesh => 1,
1632                                 flesh_fields => { ahr => [ 'current_copy', 'usr' ] }
1633                         }
1634                 ]
1635         ) or return $e->event;
1636
1637         my $user = $hold->usr;
1638         $hold->usr($user->id);
1639
1640         my $card = $e->retrieve_actor_card($user->card)
1641                 or return $e->event;
1642
1643         my( $mvr, $volume, $copy ) = find_hold_mvr($e, $hold);
1644
1645         flesh_hold_notices([$hold], $e);
1646         flesh_hold_transits([$hold]);
1647
1648         return {
1649                 hold            => $hold,
1650                 copy            => $copy,
1651                 volume  => $volume,
1652                 mvr             => $mvr,
1653                 status  => _hold_status($e, $hold),
1654                 patron_first => $user->first_given_name,
1655                 patron_last  => $user->family_name,
1656                 patron_barcode => $card->barcode,
1657         };
1658 }
1659
1660
1661
1662 # -----------------------------------------------------
1663 # Returns the MVR object that represents what the
1664 # hold is all about
1665 # -----------------------------------------------------
1666 sub find_hold_mvr {
1667         my( $e, $hold ) = @_;
1668
1669         my $tid;
1670         my $copy;
1671         my $volume;
1672
1673         if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
1674                 my $mr = $e->retrieve_metabib_metarecord($hold->target)
1675                         or return $e->event;
1676                 $tid = $mr->master_record;
1677
1678         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
1679                 $tid = $hold->target;
1680
1681         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
1682                 $volume = $e->retrieve_asset_call_number($hold->target)
1683                         or return $e->event;
1684                 $tid = $volume->record;
1685
1686         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_COPY ) {
1687                 $copy = $e->retrieve_asset_copy($hold->target)
1688                         or return $e->event;
1689                 $volume = $e->retrieve_asset_call_number($copy->call_number)
1690                         or return $e->event;
1691                 $tid = $volume->record;
1692         }
1693
1694         if(!$copy and ref $hold->current_copy ) {
1695                 $copy = $hold->current_copy;
1696                 $hold->current_copy($copy->id);
1697         }
1698
1699         if(!$volume and $copy) {
1700                 $volume = $e->retrieve_asset_call_number($copy->call_number);
1701         }
1702
1703         my $title = $e->retrieve_biblio_record_entry($tid);
1704         return ( $U->record_to_mvr($title), $volume, $copy );
1705 }
1706
1707
1708
1709
1710 1;