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