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