]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ/Holds.pm
Hold requests in the middle layer now bubble up more specific information to
[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 __PACKAGE__->register_method(
42     method    => "create_hold",
43     api_name  => "open-ils.circ.holds.create",
44     signature => {
45         desc => "Create a new hold for an item.  From a permissions perspective, " .
46                 "the login session is used as the 'requestor' of the hold.  "      . 
47                 "The hold recipient is determined by the 'usr' setting within the hold object. " .
48                 'First we verify the requestor has holds request permissions.  '         .
49                 'Then we verify that the recipient is allowed to make the given hold.  ' .
50                 'If not, we see if the requestor has "override" capabilities.  If not, ' .
51                 'a permission exception is returned.  If permissions allow, we cycle '   .
52                 'through the set of holds objects and create.  '                         .
53                 'If the recipient does not have permission to place multiple holds '     .
54                 'on a single title and said operation is attempted, a permission '       .
55                 'exception is returned',
56         params => [
57             { desc => 'Authentication token',               type => 'string' },
58             { desc => 'Hold object for hold to be created', type => 'object' }
59         ],
60         return => {
61             desc => 'Undef on success, -1 on missing arg, event (or ref to array of events) on error(s)',
62         },
63     }
64 );
65
66 __PACKAGE__->register_method(
67     method    => "create_hold",
68     api_name  => "open-ils.circ.holds.create.override",
69     notes     => '@see open-ils.circ.holds.create',
70     signature => {
71         desc  => "If the recipient is not allowed to receive the requested hold, " .
72                  "call this method to attempt the override",
73         params => [
74            { desc => 'Authentication token',               type => 'string' },
75            { desc => 'Hold object for hold to be created', type => 'object' }
76         ],
77         return => {
78             desc => 'Undef on success, -1 on missing arg, event (or ref to array of events) on error(s)',
79         },
80     }
81 );
82
83 sub create_hold {
84         my( $self, $conn, $auth, $hold ) = @_;
85         my $e = new_editor(authtoken=>$auth, xact=>1);
86         return $e->event unless $e->checkauth;
87
88     return -1 unless $hold;
89         my $override = 1 if $self->api_name =~ /override/;
90
91     my @events;
92
93     my $requestor = $e->requestor;
94     my $recipient = $requestor;
95
96     if( $requestor->id ne $hold->usr ) {
97         # Make sure the requestor is allowed to place holds for 
98         # the recipient if they are not the same people
99         $recipient = $e->retrieve_actor_user($hold->usr)  or return $e->event;
100         $e->allowed('REQUEST_HOLDS', $recipient->home_ou) or return $e->event;
101     }
102
103     # Now make sure the recipient is allowed to receive the specified hold
104     my $porg = $recipient->home_ou;
105     my $rid  = $e->requestor->id;
106     my $t    = $hold->hold_type;
107
108     # See if a duplicate hold already exists
109     my $sargs = {
110         usr                     => $recipient->id, 
111         hold_type       => $t, 
112         fulfillment_time => undef, 
113         target          => $hold->target,
114         cancel_time     => undef,
115     };
116
117     $sargs->{holdable_formats} = $hold->holdable_formats if $t eq 'M';
118         
119     my $existing = $e->search_action_hold_request($sargs); 
120     push( @events, OpenILS::Event->new('HOLD_EXISTS')) if @$existing;
121
122     my $checked_out = hold_item_is_checked_out($e, $recipient->id, $hold->hold_type, $hold->target);
123     push( @events, OpenILS::Event->new('HOLD_ITEM_CHECKED_OUT')) if $checked_out;
124
125     if ( $t eq OILS_HOLD_TYPE_METARECORD ) {
126         return $e->event unless $e->allowed('MR_HOLDS',     $porg);
127     } elsif ( $t eq OILS_HOLD_TYPE_TITLE ) {
128         return $e->event unless $e->allowed('TITLE_HOLDS',  $porg);
129     } elsif ( $t eq OILS_HOLD_TYPE_VOLUME ) {
130         return $e->event unless $e->allowed('VOLUME_HOLDS', $porg);
131     } elsif ( $t eq OILS_HOLD_TYPE_COPY ) {
132         return $e->event unless $e->allowed('COPY_HOLDS',   $porg);
133     }
134
135     if( @events ) {
136         $override or return \@events;
137         for my $evt (@events) {
138             next unless $evt;
139             my $name = $evt->{textcode};
140             return $e->event unless $e->allowed("$name.override", $porg);
141         }
142     }
143
144     # set the configured expire time
145     unless($hold->expire_time) {
146         my $interval = $U->ou_ancestor_setting_value($recipient->home_ou, OILS_SETTING_HOLD_EXPIRE);
147         if($interval) {
148             my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
149             $hold->expire_time($U->epoch2ISO8601($date->epoch));
150         }
151     }
152
153     $hold->requestor($e->requestor->id); 
154     $hold->request_lib($e->requestor->ws_ou);
155     $hold->selection_ou($hold->pickup_lib) unless $hold->selection_ou;
156     $hold = $e->create_action_hold_request($hold) or return $e->event;
157
158         $e->commit;
159
160         $conn->respond_complete($hold->id);
161
162     $U->storagereq(
163         'open-ils.storage.action.hold_request.copy_targeter', 
164         undef, $hold->id ) unless $U->is_true($hold->frozen);
165
166         return undef;
167 }
168
169 sub __create_hold {
170         my( $self, $client, $login_session, @holds) = @_;
171
172         if(!@holds){return 0;}
173         my( $user, $evt ) = $apputils->checkses($login_session);
174         return $evt if $evt;
175
176         my $holdsref = (ref($holds[0]) eq 'ARRAY') ? $holds[0] : [ @holds ];
177
178         $logger->debug("Iterating over " . scalar(@$holdsref) . " holds requests...");
179
180         for my $hold (@$holdsref) {
181         $hold or 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                 } else {
192                         $recipient = $user;
193                 }
194
195                 # am I allowed to place holds for this user?
196                 if($hold->requestor ne $hold->usr) {
197                         my $perm = _check_request_holds_perm($user->id, $user->home_ou);
198             return $perm if $perm;
199                 }
200
201                 # is this user allowed to have holds of this type?
202                 my $perm = _check_holds_perm($type, $hold->requestor, $recipient->home_ou);
203         return $perm if $perm;
204
205                 #enforce the fact that the login is the one requesting the hold
206                 $hold->requestor($user->id); 
207                 $hold->selection_ou($recipient->home_ou) unless $hold->selection_ou;
208
209                 my $resp = $apputils->simplereq(
210                         'open-ils.storage',
211                         'open-ils.storage.direct.action.hold_request.create', $hold );
212
213                 if(!$resp) { 
214                         return OpenSRF::EX::ERROR ("Error creating hold"); 
215                 }
216         }
217
218         return 1;
219 }
220
221 # makes sure that a user has permission to place the type of requested hold
222 # returns the Perm exception if not allowed, returns undef if all is well
223 sub _check_holds_perm {
224         my($type, $user_id, $org_id) = @_;
225
226         my $evt;
227         if ($type eq "M") {
228                 $evt = $apputils->check_perms($user_id, $org_id, "MR_HOLDS"    );
229         } elsif ($type eq "T") {
230                 $evt = $apputils->check_perms($user_id, $org_id, "TITLE_HOLDS" );
231         } elsif($type eq "V") {
232                 $evt = $apputils->check_perms($user_id, $org_id, "VOLUME_HOLDS");
233         } elsif($type eq "C") {
234                 $evt = $apputils->check_perms($user_id, $org_id, "COPY_HOLDS"  );
235         }
236
237     return $evt if $evt;
238         return undef;
239 }
240
241 # tests if the given user is allowed to place holds on another's behalf
242 sub _check_request_holds_perm {
243         my $user_id = shift;
244         my $org_id  = shift;
245         if (my $evt = $apputils->check_perms(
246                 $user_id, $org_id, "REQUEST_HOLDS")) {
247                 return $evt;
248         }
249 }
250
251 my $ses_is_req_note = 'The login session is the requestor.  If the requestor is different from the user, ' .
252                       'then the requestor must have VIEW_HOLD permissions';
253
254 __PACKAGE__->register_method(
255     method    => "retrieve_holds_by_id",
256     api_name  => "open-ils.circ.holds.retrieve_by_id",
257     signature => {
258         desc   => "Retrieve the hold, with hold transits attached, for the specified ID.  $ses_is_req_note",
259         params => [
260             { desc => 'Authentication token', type => 'string' },
261             { desc => 'Hold ID',              type => 'number' }
262         ],
263         return => {
264             desc => 'Hold object with transits attached, event on error',
265         }
266     }
267 );
268
269
270 sub retrieve_holds_by_id {
271         my($self, $client, $auth, $hold_id) = @_;
272         my $e = new_editor(authtoken=>$auth);
273         $e->checkauth or return $e->event;
274         $e->allowed('VIEW_HOLD') or return $e->event;
275
276         my $holds = $e->search_action_hold_request(
277                 [
278                         { id =>  $hold_id , fulfillment_time => undef }, 
279                         { 
280                 order_by => { ahr => "request_time" },
281                 flesh => 1,
282                 flesh_fields => {ahr => ['notes']}
283             }
284                 ]
285         );
286
287         flesh_hold_transits($holds);
288         flesh_hold_notices($holds, $e);
289         return $holds;
290 }
291
292
293 __PACKAGE__->register_method(
294     method    => "retrieve_holds",
295     api_name  => "open-ils.circ.holds.retrieve",
296     signature => {
297         desc   => "Retrieves all the holds, with hold transits attached, for the specified user.  $ses_is_req_note",
298         params => [
299             { desc => 'Authentication token', type => 'string'  },
300             { desc => 'User ID',              type => 'integer' }
301         ],
302         return => {
303             desc => 'list of holds, event on error',
304         }
305    }
306 );
307
308 __PACKAGE__->register_method(
309     method        => "retrieve_holds",
310     api_name      => "open-ils.circ.holds.id_list.retrieve",
311     authoritative => 1,
312     signature     => {
313         desc   => "Retrieves all the hold IDs, for the specified user.  $ses_is_req_note",
314         params => [
315             { desc => 'Authentication token', type => 'string'  },
316             { desc => 'User ID',              type => 'integer' }
317         ],
318         return => {
319             desc => 'list of holds, event on error',
320         }
321    }
322 );
323
324 __PACKAGE__->register_method(
325     method        => "retrieve_holds",
326     api_name      => "open-ils.circ.holds.canceled.retrieve",
327     authoritative => 1,
328     signature     => {
329         desc   => "Retrieves all the cancelled holds for the specified user.  $ses_is_req_note",
330         params => [
331             { desc => 'Authentication token', type => 'string'  },
332             { desc => 'User ID',              type => 'integer' }
333         ],
334         return => {
335             desc => 'list of holds, event on error',
336         }
337    }
338 );
339
340 __PACKAGE__->register_method(
341     method        => "retrieve_holds",
342     api_name      => "open-ils.circ.holds.canceled.id_list.retrieve",
343     authoritative => 1,
344     signature     => {
345         desc   => "Retrieves list of cancelled hold IDs for the specified user.  $ses_is_req_note",
346         params => [
347             { desc => 'Authentication token', type => 'string'  },
348             { desc => 'User ID',              type => 'integer' }
349         ],
350         return => {
351             desc => 'list of hold IDs, event on error',
352         }
353    }
354 );
355
356
357 sub retrieve_holds {
358     my ($self, $client, $auth, $user_id) = @_;
359
360     my $e = new_editor(authtoken=>$auth);
361     return $e->event unless $e->checkauth;
362     $user_id = $e->requestor->id unless defined $user_id;
363
364     my $notes_filter = {staff => 'f'};
365     my $user = $e->retrieve_actor_user($user_id) or return $e->event;
366     unless($user_id == $e->requestor->id) {
367         if($e->allowed('VIEW_HOLD', $user->home_ou)) {
368             $notes_filter = {staff => 't'}
369         } else {
370             my $allowed = OpenILS::Application::Actor::Friends->friend_perm_allowed(
371                 $e, $user_id, $e->requestor->id, 'hold.view');
372             return $e->event unless $allowed;
373         }
374     } else {
375         # staff member looking at his/her own holds can see staff and non-staff notes
376         $notes_filter = {} if $e->allowed('VIEW_HOLD', $user->home_ou);
377     }
378
379     my $holds;
380
381     if($self->api_name !~ /canceled/) {
382
383         # Fetch the active holds
384
385         $holds = $e->search_action_hold_request([
386             {   usr =>  $user_id , 
387                 fulfillment_time => undef,
388                 cancel_time      => undef,
389             }, 
390             {order_by => {ahr => "request_time"}}
391         ]);
392
393     } else {
394
395         # Fetch the canceled holds
396
397         my $cancel_age;
398         my $cancel_count = $U->ou_ancestor_setting_value(
399                 $e->requestor->ws_ou, 'circ.holds.canceled.display_count', $e);
400
401         unless($cancel_count) {
402             $cancel_age = $U->ou_ancestor_setting_value(
403                 $e->requestor->ws_ou, 'circ.holds.canceled.display_age', $e);
404         }
405
406         if($cancel_count) { # limit by count
407
408             # find at most cancel_count canceled holds
409             $holds = $e->search_action_hold_request([
410                 {   usr =>  $user_id , 
411                     fulfillment_time => undef,
412                     cancel_time      => {'!=' => undef},
413                 }, 
414                 {order_by => {ahr => "cancel_time desc"}, limit => $cancel_count}
415             ]);
416
417         } elsif($cancel_age) { # limit by age
418
419             # find all of the canceled holds that were canceled within the configured time frame
420             my $date = DateTime->now->subtract(seconds => OpenSRF::Utils::interval_to_seconds($cancel_age));
421             $date = $U->epoch2ISO8601($date->epoch);
422
423             $holds = $e->search_action_hold_request([
424                 {   usr =>  $user_id , 
425                     fulfillment_time => undef,
426                     cancel_time      => {'>=' => $date},
427                 }, 
428                 {order_by => {ahr => "cancel_time desc"}}
429             ]);
430         }
431     }
432
433     if( $self->api_name !~ /id_list/ ) {
434         for my $hold ( @$holds ) {
435             $hold->notes($e->search_action_hold_request_note({hold => $hold->id, %$notes_filter}));
436             $hold->transit(
437                 $e->search_action_hold_transit_copy([
438                     {hold => $hold->id},
439                     {order_by => {ahtc => 'id desc'}, limit => 1}])->[0]
440             );
441         }
442         return $holds;
443     }
444     # else id_list
445     return [ map { $_->id } @$holds ];
446 }
447
448
449 __PACKAGE__->register_method(
450     method   => 'user_hold_count',
451     api_name => 'open-ils.circ.hold.user.count'
452 );
453
454 sub user_hold_count {
455     my ( $self, $conn, $auth, $userid ) = @_;
456     my $e = new_editor( authtoken => $auth );
457     return $e->event unless $e->checkauth;
458     my $patron = $e->retrieve_actor_user($userid)
459         or return $e->event;
460     return $e->event unless $e->allowed( 'VIEW_HOLD', $patron->home_ou );
461     return __user_hold_count( $self, $e, $userid );
462 }
463
464 sub __user_hold_count {
465     my ( $self, $e, $userid ) = @_;
466     my $holds = $e->search_action_hold_request(
467         {
468             usr              => $userid,
469             fulfillment_time => undef,
470             cancel_time      => undef,
471         },
472         { idlist => 1 }
473     );
474
475     return scalar(@$holds);
476 }
477
478
479 __PACKAGE__->register_method(
480     method   => "retrieve_holds_by_pickup_lib",
481     api_name => "open-ils.circ.holds.retrieve_by_pickup_lib",
482     notes    => 
483       "Retrieves all the holds, with hold transits attached, for the specified pickup_ou id."
484 );
485
486 __PACKAGE__->register_method(
487     method   => "retrieve_holds_by_pickup_lib",
488     api_name => "open-ils.circ.holds.id_list.retrieve_by_pickup_lib",
489     notes    => "Retrieves all the hold ids for the specified pickup_ou id. "
490 );
491
492 sub retrieve_holds_by_pickup_lib {
493     my ($self, $client, $login_session, $ou_id) = @_;
494
495     #FIXME -- put an appropriate permission check here
496     #my( $user, $target, $evt ) = $apputils->checkses_requestor(
497     #   $login_session, $user_id, 'VIEW_HOLD' );
498     #return $evt if $evt;
499
500         my $holds = $apputils->simplereq(
501                 'open-ils.cstore',
502                 "open-ils.cstore.direct.action.hold_request.search.atomic",
503                 { 
504                         pickup_lib =>  $ou_id , 
505                         fulfillment_time => undef,
506                         cancel_time => undef
507                 }, 
508                 { order_by => { ahr => "request_time" } }
509     );
510
511     if ( ! $self->api_name =~ /id_list/ ) {
512         flesh_hold_transits($holds);
513         return $holds;
514     }
515     # else id_list
516     return [ map { $_->id } @$holds ];
517 }
518
519
520 __PACKAGE__->register_method(
521     method   => "uncancel_hold",
522     api_name => "open-ils.circ.hold.uncancel"
523 );
524
525 sub uncancel_hold {
526         my($self, $client, $auth, $hold_id) = @_;
527         my $e = new_editor(authtoken=>$auth, xact=>1);
528         return $e->event unless $e->checkauth;
529
530         my $hold = $e->retrieve_action_hold_request($hold_id)
531                 or return $e->die_event;
532     return $e->die_event unless $e->allowed('CANCEL_HOLDS', $hold->request_lib);
533
534     return 0 if $hold->fulfillment_time;
535     return 1 unless $hold->cancel_time;
536
537     # if configured to reset the request time, also reset the expire time
538     if($U->ou_ancestor_setting_value(
539         $hold->request_lib, 'circ.holds.uncancel.reset_request_time', $e)) {
540
541         $hold->request_time('now');
542         my $interval = $U->ou_ancestor_setting_value($hold->request_lib, OILS_SETTING_HOLD_EXPIRE);
543         if($interval) {
544             my $date = DateTime->now->add(seconds => OpenSRF::Utils::interval_to_seconds($interval));
545             $hold->expire_time($U->epoch2ISO8601($date->epoch));
546         }
547     }
548
549     $hold->clear_cancel_time;
550     $hold->clear_cancel_cause;
551     $hold->clear_cancel_note;
552     $e->update_action_hold_request($hold) or return $e->die_event;
553     $e->commit;
554
555     $U->storagereq('open-ils.storage.action.hold_request.copy_targeter', undef, $hold_id);
556
557     return 1;
558 }
559
560
561 __PACKAGE__->register_method(
562     method    => "cancel_hold",
563     api_name  => "open-ils.circ.hold.cancel",
564     signature => {
565         desc   => 'Cancels the specified hold.  The login session is the requestor.  If the requestor is different from the usr field ' .
566                   'on the hold, the requestor must have CANCEL_HOLDS permissions. The hold may be either the hold object or the hold id',
567         param  => [
568             {desc => 'Authentication token',  type => 'string'},
569             {desc => 'Hold ID',               type => 'number'},
570             {desc => 'Cause of Cancellation', type => 'string'},
571             {desc => 'Note',                  type => 'string'}
572         ],
573         return => {
574             desc => '1 on success, event on error'
575         }
576     }
577 );
578
579 sub cancel_hold {
580         my($self, $client, $auth, $holdid, $cause, $note) = @_;
581
582         my $e = new_editor(authtoken=>$auth, xact=>1);
583         return $e->event unless $e->checkauth;
584
585         my $hold = $e->retrieve_action_hold_request($holdid)
586                 or return $e->event;
587
588         if( $e->requestor->id ne $hold->usr ) {
589                 return $e->event unless $e->allowed('CANCEL_HOLDS');
590         }
591
592         return 1 if $hold->cancel_time;
593
594         # If the hold is captured, reset the copy status
595         if( $hold->capture_time and $hold->current_copy ) {
596
597                 my $copy = $e->retrieve_asset_copy($hold->current_copy)
598                         or return $e->event;
599
600                 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
601          $logger->info("canceling hold $holdid whose item is on the holds shelf");
602 #                       $logger->info("setting copy to status 'reshelving' on hold cancel");
603 #                       $copy->status(OILS_COPY_STATUS_RESHELVING);
604 #                       $copy->editor($e->requestor->id);
605 #                       $copy->edit_date('now');
606 #                       $e->update_asset_copy($copy) or return $e->event;
607
608                 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
609
610                         my $hid = $hold->id;
611                         $logger->warn("! canceling hold [$hid] that is in transit");
612                         my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
613
614                         if( $transid ) {
615                                 my $trans = $e->retrieve_action_transit_copy($transid);
616                                 # Leave the transit alive, but  set the copy status to 
617                                 # reshelving so it will be properly reshelved when it gets back home
618                                 if( $trans ) {
619                                         $trans->copy_status( OILS_COPY_STATUS_RESHELVING );
620                                         $e->update_action_transit_copy($trans) or return $e->die_event;
621                                 }
622                         }
623                 }
624         }
625
626         $hold->cancel_time('now');
627     $hold->cancel_cause($cause);
628     $hold->cancel_note($note);
629         $e->update_action_hold_request($hold)
630                 or return $e->event;
631
632         delete_hold_copy_maps($self, $e, $hold->id);
633
634         $e->commit;
635         return 1;
636 }
637
638 sub delete_hold_copy_maps {
639         my $class  = shift;
640         my $editor = shift;
641         my $holdid = shift;
642
643         my $maps = $editor->search_action_hold_copy_map({hold=>$holdid});
644         for(@$maps) {
645                 $editor->delete_action_hold_copy_map($_) 
646                         or return $editor->event;
647         }
648         return undef;
649 }
650
651
652 my $update_hold_desc = 'The login session is the requestor. '       .
653    'If the requestor is different from the usr field on the hold, ' .
654    'the requestor must have UPDATE_HOLDS permissions. '             .
655    'If supplying a hash of hold data, "id" must be included. '      .
656    'The hash is ignored if a hold object is supplied, '             .
657    'so you should supply only one kind of hold data argument.'      ;
658
659 __PACKAGE__->register_method(
660     method    => "update_hold",
661     api_name  => "open-ils.circ.hold.update",
662     signature => {
663         desc   => "Updates the specified hold.  $update_hold_desc",
664         params => [
665             {desc => 'Authentication token',         type => 'string'},
666             {desc => 'Hold Object',                  type => 'object'},
667             {desc => 'Hash of values to be applied', type => 'object'}
668         ],
669         return => {
670             desc => 'Hold ID on success, event on error',
671             # type => 'number'
672         }
673     }
674 );
675
676 __PACKAGE__->register_method(
677     method    => "batch_update_hold",
678     api_name  => "open-ils.circ.hold.update.batch",
679     stream    => 1,
680     signature => {
681         desc   => "Updates the specified hold(s).  $update_hold_desc",
682         params => [
683             {desc => 'Authentication token',                    type => 'string'},
684             {desc => 'Array of hold obejcts',                   type => 'array' },
685             {desc => 'Array of hashes of values to be applied', type => 'array' }
686         ],
687         return => {
688             desc => 'Hold ID per success, event per error',
689         }
690     }
691 );
692
693 sub update_hold {
694         my($self, $client, $auth, $hold, $values) = @_;
695     my $e = new_editor(authtoken=>$auth, xact=>1);
696     return $e->die_event unless $e->checkauth;
697     my $resp = update_hold_impl($self, $e, $hold, $values);
698     return $resp if $U->event_code($resp);
699     $e->commit;     # FIXME: update_hold_impl already does $e->commit  ??
700     return $resp;
701 }
702
703 sub batch_update_hold {
704         my($self, $client, $auth, $hold_list, $values_list) = @_;
705     my $e = new_editor(authtoken=>$auth);
706     return $e->die_event unless $e->checkauth;
707
708     my $count = ($hold_list) ? scalar(@$hold_list) : scalar(@$values_list);     # FIXME: we don't know for sure that we got $values_list.  we could have neither list.
709     $hold_list   ||= [];
710     $values_list ||= [];      # FIXME: either move this above $count declaration, or send an event if both lists undef.  Probably the latter.
711
712 # FIXME: Failing over to [] guarantees warnings for "Use of unitialized value" in update_hold_impl call.
713 # FIXME: We should be sure we only call update_hold_impl with hold object OR hash, not both.
714
715     for my $idx (0..$count-1) {
716         $e->xact_begin;
717         my $resp = update_hold_impl($self, $e, $hold_list->[$idx], $values_list->[$idx]);
718         $e->xact_commit unless $U->event_code($resp);
719         $client->respond($resp);
720     }
721
722     $e->disconnect;
723     return undef;       # not in the register return type, assuming we should always have at least one list populated
724 }
725
726 sub update_hold_impl {
727     my($self, $e, $hold, $values) = @_;
728
729     unless($hold) {
730         $hold = $e->retrieve_action_hold_request($values->{id})
731             or return $e->die_event;
732         $hold->$_($values->{$_}) for keys %$values;
733     }
734
735     my $orig_hold = $e->retrieve_action_hold_request($hold->id)
736         or return $e->die_event;
737
738     # don't allow the user to be changed
739     return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
740
741     if($hold->usr ne $e->requestor->id) {
742         # if the hold is for a different user, make sure the 
743         # requestor has the appropriate permissions
744         my $usr = $e->retrieve_actor_user($hold->usr)
745             or return $e->die_event;
746         return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
747     }
748
749
750     # --------------------------------------------------------------
751     # Changing the request time is like playing God
752     # --------------------------------------------------------------
753     if($hold->request_time ne $orig_hold->request_time) {
754         return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
755         return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
756     }
757
758     # --------------------------------------------------------------
759     # if the hold is on the holds shelf or in transit and the pickup 
760     # lib changes we need to create a new transit.
761     # --------------------------------------------------------------
762     if($orig_hold->pickup_lib ne $hold->pickup_lib) {
763
764         my $status = _hold_status($e, $hold);
765
766         if($status == 3) { # in transit
767
768             return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
769             return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
770
771             $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
772
773             # update the transit to reflect the new pickup location
774                         my $transit = $e->search_action_hold_transit_copy(
775                 {hold=>$hold->id, dest_recv_time => undef})->[0] 
776                 or return $e->die_event;
777
778             $transit->prev_dest($transit->dest); # mark the previous destination on the transit
779             $transit->dest($hold->pickup_lib);
780             $e->update_action_hold_transit_copy($transit) or return $e->die_event;
781
782         } elsif($status == 4) { # on holds shelf
783
784             return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
785             return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
786
787             $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
788
789             # create the new transit
790             my $evt = transit_hold($e, $orig_hold, $hold, $e->retrieve_asset_copy($hold->current_copy));
791             return $evt if $evt;
792         }
793     } 
794
795     update_hold_if_frozen($self, $e, $hold, $orig_hold);
796     $e->update_action_hold_request($hold) or return $e->die_event;
797     $e->commit;
798
799     # a change to mint-condition changes the set of potential copies, so retarget the hold;
800     if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
801         _reset_hold($self, $e->requestor, $hold) 
802     }
803
804     return $hold->id;
805 }
806
807 sub transit_hold {
808     my($e, $orig_hold, $hold, $copy) = @_;
809     my $src  = $orig_hold->pickup_lib;
810     my $dest = $hold->pickup_lib;
811
812     $logger->info("putting hold into transit on pickup_lib update");
813
814     my $transit = Fieldmapper::action::hold_transit_copy->new;
815     $transit->hold($hold->id);
816     $transit->source($src);
817     $transit->dest($dest);
818     $transit->target_copy($copy->id);
819     $transit->source_send_time('now');
820     $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
821
822     $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
823     $copy->editor($e->requestor->id);
824     $copy->edit_date('now');
825
826     $e->create_action_hold_transit_copy($transit) or return $e->die_event;
827     $e->update_asset_copy($copy) or return $e->die_event;
828     return undef;
829 }
830
831 # if the hold is frozen, this method ensures that the hold is not "targeted", 
832 # that is, it clears the current_copy and prev_check_time to essentiallly 
833 # reset the hold.  If it is being activated, it runs the targeter in the background
834 sub update_hold_if_frozen {
835     my($self, $e, $hold, $orig_hold) = @_;
836     return if $hold->capture_time;
837
838     if($U->is_true($hold->frozen)) {
839         $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
840         $hold->clear_current_copy;
841         $hold->clear_prev_check_time;
842
843     } else {
844         if($U->is_true($orig_hold->frozen)) {
845             $logger->info("Running targeter on activated hold ".$hold->id);
846             $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
847         }
848     }
849 }
850
851 __PACKAGE__->register_method(
852     method    => "hold_note_CUD",
853     api_name  => "open-ils.circ.hold_request.note.cud",
854     signature => {
855         desc   => 'Create, update or delete a hold request note.  If the operator (from Auth. token) '
856                 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
857         params => [
858             { desc => 'Authentication token', type => 'string' },
859             { desc => 'Hold note object',     type => 'object' }
860         ],
861         return => {
862             desc => 'Returns the note ID, event on error'
863         },
864     }
865 );
866
867 sub hold_note_CUD {
868         my($self, $conn, $auth, $note) = @_;
869
870     my $e = new_editor(authtoken => $auth, xact => 1);
871     return $e->die_event unless $e->checkauth;
872
873     my $hold = $e->retrieve_action_hold_request($note->hold)
874         or return $e->die_event;
875
876     if($hold->usr ne $e->requestor->id) {
877         my $usr = $e->retrieve_actor_user($hold->usr);
878         return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
879         $note->staff('t') if $note->isnew;
880     }
881
882     if($note->isnew) {
883         $e->create_action_hold_request_note($note) or return $e->die_event;
884     } elsif($note->ischanged) {
885         $e->update_action_hold_request_note($note) or return $e->die_event;
886     } elsif($note->isdeleted) {
887         $e->delete_action_hold_request_note($note) or return $e->die_event;
888     }
889
890     $e->commit;
891     return $note->id;
892 }
893
894
895 __PACKAGE__->register_method(
896     method    => "retrieve_hold_status",
897     api_name  => "open-ils.circ.hold.status.retrieve",
898     signature => {
899         desc   => 'Calculates the current status of the hold. The requestor must have '      .
900                   'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
901         param  => [
902             { desc => 'Hold ID', type => 'number' }
903         ],
904         return => {
905             # type => 'number',     # event sometimes
906             desc => <<'END_OF_DESC'
907 Returns event on error or:
908 -1 on error (for now),
909  1 for 'waiting for copy to become available',
910  2 for 'waiting for copy capture',
911  3 for 'in transit',
912  4 for 'arrived',
913  5 for 'hold-shelf-delay'
914 END_OF_DESC
915         }
916     }
917 );
918
919 sub retrieve_hold_status {
920         my($self, $client, $auth, $hold_id) = @_;
921
922         my $e = new_editor(authtoken => $auth);
923         return $e->event unless $e->checkauth;
924         my $hold = $e->retrieve_action_hold_request($hold_id)
925                 or return $e->event;
926
927         if( $e->requestor->id != $hold->usr ) {
928                 return $e->event unless $e->allowed('VIEW_HOLD');
929         }
930
931         return _hold_status($e, $hold);
932
933 }
934
935 sub _hold_status {
936         my($e, $hold) = @_;
937         return 1 unless $hold->current_copy;
938         return 2 unless $hold->capture_time;
939
940         my $copy = $hold->current_copy;
941         unless( ref $copy ) {
942                 $copy = $e->retrieve_asset_copy($hold->current_copy)
943                         or return $e->event;
944         }
945
946         return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
947
948         if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
949
950         my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
951         return 4 unless $hs_wait_interval;
952
953         # if a hold_shelf_status_delay interval is defined and start_time plus 
954         # the interval is greater than now, consider the hold to be in the virtual 
955         # "on its way to the holds shelf" status. Return 5.
956
957         my $transit    = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
958         my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
959         $start_time    = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
960         my $end_time   = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
961
962         return 5 if $end_time > DateTime->now;
963         return 4;
964     }
965
966     return -1;  # error
967 }
968
969
970
971 __PACKAGE__->register_method(
972     method    => "retrieve_hold_queue_stats",
973     api_name  => "open-ils.circ.hold.queue_stats.retrieve",
974     signature => {
975         desc   => 'Returns summary data about the state of a hold',
976         params => [
977             { desc => 'Authentication token',  type => 'string'},
978             { desc => 'Hold ID', type => 'number'},
979         ],
980         return => {
981             desc => q/Summary object with keys: 
982                 total_holds : total holds in queue
983                 queue_position : current queue position
984                 potential_copies : number of potential copies for this hold
985                 estimated_wait : estimated wait time in days
986                 status : hold status  
987                      -1 => error or unexpected state,
988                      1 => 'waiting for copy to become available',
989                      2 => 'waiting for copy capture',
990                      3 => 'in transit',
991                      4 => 'arrived',
992                      5 => 'hold-shelf-delay'
993             /,
994             type => 'object'
995         }
996     }
997 );
998
999 sub retrieve_hold_queue_stats {
1000     my($self, $conn, $auth, $hold_id) = @_;
1001         my $e = new_editor(authtoken => $auth);
1002         return $e->event unless $e->checkauth;
1003         my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1004         if($e->requestor->id != $hold->usr) {
1005                 return $e->event unless $e->allowed('VIEW_HOLD');
1006         }
1007     return retrieve_hold_queue_status_impl($e, $hold);
1008 }
1009
1010 sub retrieve_hold_queue_status_impl {
1011     my $e = shift;
1012     my $hold = shift;
1013
1014     # The holds queue is defined as the distinct set of holds that share at 
1015     # least one potential copy with the context hold, plus any holds that
1016     # share the same hold type and target.  The latter part exists to
1017     # accomodate holds that currently have no potential copies
1018     my $q_holds = $e->json_query({
1019
1020         # fetch request_time since it's in the order_by and we're asking for distinct values
1021         select => {ahr => ['id', 'request_time']},
1022         from   => {
1023             ahr => {
1024                 ahcm => {type => 'left'} # there may be no copy maps 
1025             }
1026         },
1027         order_by => {ahr => ['request_time']},
1028         distinct => 1,
1029         where    => {
1030             '-or' => [
1031                 {
1032                     '+ahcm' => {
1033                         target_copy => {
1034                             in => {
1035                                 select => {ahcm => ['target_copy']},
1036                                 from   => 'ahcm',
1037                                 where  => {hold => $hold->id}
1038                             } 
1039                         } 
1040                     }
1041                 },
1042                 {
1043                     '+ahr' => {
1044                         hold_type => $hold->hold_type,
1045                         target    => $hold->target
1046                     }
1047                 }
1048             ]
1049         }, 
1050     });
1051
1052     my $qpos = 1;
1053     for my $h (@$q_holds) {
1054         last if $h->{id} == $hold->id;
1055         $qpos++;
1056     }
1057
1058     my $hold_data = $e->json_query({
1059         select => {
1060             ccm => [
1061                 {column => 'code', transform => 'count', aggregate => 1, alias => 'count'}, 
1062                 {column =>'avg_wait_time'}
1063             ]
1064         }, 
1065         from => {ahcm => {acp => {join => 'ccm'}}}, 
1066         where => {'+ahcm' => {hold => $hold->id}}
1067     });
1068
1069     my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1070
1071     my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1072     my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1073     $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1074     $default_wait ||= '0 seconds';
1075
1076     # Estimated wait time is the average wait time across the set 
1077     # of potential copies, divided by the number of potential copies
1078     # times the queue position.  
1079
1080     my $combined_secs = 0;
1081     my $num_potentials = 0;
1082
1083     for my $wait_data (@$hold_data) {
1084         my $count += $wait_data->{count};
1085         $combined_secs += $count * 
1086             OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1087         $num_potentials += $count;
1088     }
1089
1090     my $estimated_wait = -1;
1091
1092     if($num_potentials) {
1093         my $avg_wait = $combined_secs / $num_potentials;
1094         $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1095         $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1096     }
1097
1098     return {
1099         total_holds      => scalar(@$q_holds),
1100         queue_position   => $qpos,
1101         potential_copies => $num_potentials,
1102         status           => _hold_status( $e, $hold ),
1103         estimated_wait   => int($estimated_wait)
1104     };
1105 }
1106
1107
1108 sub fetch_open_hold_by_current_copy {
1109         my $class = shift;
1110         my $copyid = shift;
1111         my $hold = $apputils->simplereq(
1112                 'open-ils.cstore', 
1113                 'open-ils.cstore.direct.action.hold_request.search.atomic',
1114                 { current_copy =>  $copyid , cancel_time => undef, fulfillment_time => undef });
1115         return $hold->[0] if ref($hold);
1116         return undef;
1117 }
1118
1119 sub fetch_related_holds {
1120         my $class = shift;
1121         my $copyid = shift;
1122         return $apputils->simplereq(
1123                 'open-ils.cstore', 
1124                 'open-ils.cstore.direct.action.hold_request.search.atomic',
1125                 { current_copy =>  $copyid , cancel_time => undef, fulfillment_time => undef });
1126 }
1127
1128
1129 __PACKAGE__->register_method(
1130     method    => "hold_pull_list",
1131     api_name  => "open-ils.circ.hold_pull_list.retrieve",
1132     signature => {
1133         desc   => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1134                   'The location is determined by the login session.',
1135         params => [
1136             { desc => 'Limit (optional)',  type => 'number'},
1137             { desc => 'Offset (optional)', type => 'number'},
1138         ],
1139         return => {
1140             desc => 'reference to a list of holds, or event on failure',
1141         }
1142     }
1143 );
1144
1145 __PACKAGE__->register_method(
1146     method    => "hold_pull_list",
1147     api_name  => "open-ils.circ.hold_pull_list.id_list.retrieve",
1148     signature => {
1149         desc   => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1150                   'The location is determined by the login session.',
1151         params => [
1152             { desc => 'Limit (optional)',  type => 'number'},
1153             { desc => 'Offset (optional)', type => 'number'},
1154         ],
1155         return => {
1156             desc => 'reference to a list of holds, or event on failure',
1157         }
1158     }
1159 );
1160
1161 __PACKAGE__->register_method(
1162     method    => "hold_pull_list",
1163     api_name  => "open-ils.circ.hold_pull_list.retrieve.count",
1164     signature => {
1165         desc   => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1166                   'The location is determined by the login session.',
1167         params => [
1168             { desc => 'Limit (optional)',  type => 'number'},
1169             { desc => 'Offset (optional)', type => 'number'},
1170         ],
1171         return => {
1172             desc => 'Holds count (integer), or event on failure',
1173             # type => 'number'
1174         }
1175     }
1176 );
1177
1178
1179 sub hold_pull_list {
1180         my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1181         my( $reqr, $evt ) = $U->checkses($authtoken);
1182         return $evt if $evt;
1183
1184         my $org = $reqr->ws_ou || $reqr->home_ou;
1185         # the perm locaiton shouldn't really matter here since holds
1186         # will exist all over and VIEW_HOLDS should be universal
1187         $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1188         return $evt if $evt;
1189
1190     if($self->api_name =~ /count/) {
1191
1192                 my $count = $U->storagereq(
1193                         'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1194                         $org, $limit, $offset ); 
1195
1196         $logger->info("Grabbing pull list for org unit $org with $count items");
1197         return $count;
1198
1199     } elsif( $self->api_name =~ /id_list/ ) {
1200                 return $U->storagereq(
1201                         'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1202                         $org, $limit, $offset ); 
1203
1204         } else {
1205                 return $U->storagereq(
1206                         'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1207                         $org, $limit, $offset ); 
1208         }
1209 }
1210
1211 __PACKAGE__->register_method(
1212     method        => 'fetch_hold_notify',
1213     api_name      => 'open-ils.circ.hold_notification.retrieve_by_hold',
1214     authoritative => 1,
1215     signature     => q/ 
1216 Returns a list of hold notification objects based on hold id.
1217 @param authtoken The loggin session key
1218 @param holdid The id of the hold whose notifications we want to retrieve
1219 @return An array of hold notification objects, event on error.
1220 /
1221 );
1222
1223 sub fetch_hold_notify {
1224         my( $self, $conn, $authtoken, $holdid ) = @_;
1225         my( $requestor, $evt ) = $U->checkses($authtoken);
1226         return $evt if $evt;
1227         my ($hold, $patron);
1228         ($hold, $evt) = $U->fetch_hold($holdid);
1229         return $evt if $evt;
1230         ($patron, $evt) = $U->fetch_user($hold->usr);
1231         return $evt if $evt;
1232
1233         $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1234         return $evt if $evt;
1235
1236         $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1237         return $U->cstorereq(
1238                 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1239 }
1240
1241
1242 __PACKAGE__->register_method(
1243     method    => 'create_hold_notify',
1244     api_name  => 'open-ils.circ.hold_notification.create',
1245     signature => q/
1246 Creates a new hold notification object
1247 @param authtoken The login session key
1248 @param notification The hold notification object to create
1249 @return ID of the new object on success, Event on error
1250 /
1251 );
1252
1253 sub create_hold_notify {
1254    my( $self, $conn, $auth, $note ) = @_;
1255    my $e = new_editor(authtoken=>$auth, xact=>1);
1256    return $e->die_event unless $e->checkauth;
1257
1258    my $hold = $e->retrieve_action_hold_request($note->hold)
1259       or return $e->die_event;
1260    my $patron = $e->retrieve_actor_user($hold->usr) 
1261       or return $e->die_event;
1262
1263    return $e->die_event unless 
1264       $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1265
1266         $note->notify_staff($e->requestor->id);
1267    $e->create_action_hold_notification($note) or return $e->die_event;
1268    $e->commit;
1269    return $note->id;
1270 }
1271
1272 __PACKAGE__->register_method(
1273     method    => 'create_hold_note',
1274     api_name  => 'open-ils.circ.hold_note.create',
1275     signature => q/
1276                 Creates a new hold request note object
1277                 @param authtoken The login session key
1278                 @param note The hold note object to create
1279                 @return ID of the new object on success, Event on error
1280                 /
1281 );
1282
1283 sub create_hold_note {
1284    my( $self, $conn, $auth, $note ) = @_;
1285    my $e = new_editor(authtoken=>$auth, xact=>1);
1286    return $e->die_event unless $e->checkauth;
1287
1288    my $hold = $e->retrieve_action_hold_request($note->hold)
1289       or return $e->die_event;
1290    my $patron = $e->retrieve_actor_user($hold->usr) 
1291       or return $e->die_event;
1292
1293    return $e->die_event unless 
1294       $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn.  Probably want something more specific
1295
1296    $e->create_action_hold_request_note($note) or return $e->die_event;
1297    $e->commit;
1298    return $note->id;
1299 }
1300
1301 __PACKAGE__->register_method(
1302     method    => 'reset_hold',
1303     api_name  => 'open-ils.circ.hold.reset',
1304     signature => q/
1305                 Un-captures and un-targets a hold, essentially returning
1306                 it to the state it was in directly after it was placed,
1307                 then attempts to re-target the hold
1308                 @param authtoken The login session key
1309                 @param holdid The id of the hold
1310         /
1311 );
1312
1313
1314 sub reset_hold {
1315         my( $self, $conn, $auth, $holdid ) = @_;
1316         my $reqr;
1317         my ($hold, $evt) = $U->fetch_hold($holdid);
1318         return $evt if $evt;
1319         ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1320         return $evt if $evt;
1321         $evt = _reset_hold($self, $reqr, $hold);
1322         return $evt if $evt;
1323         return 1;
1324 }
1325
1326
1327 __PACKAGE__->register_method(
1328     method   => 'reset_hold_batch',
1329     api_name => 'open-ils.circ.hold.reset.batch'
1330 );
1331
1332 sub reset_hold_batch {
1333     my($self, $conn, $auth, $hold_ids) = @_;
1334
1335     my $e = new_editor(authtoken => $auth);
1336     return $e->event unless $e->checkauth;
1337
1338     for my $hold_id ($hold_ids) {
1339
1340         my $hold = $e->retrieve_action_hold_request(
1341             [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}]) 
1342             or return $e->event;
1343
1344             next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1345         _reset_hold($self, $e->requestor, $hold);
1346     }
1347
1348     return 1;
1349 }
1350
1351
1352 sub _reset_hold {
1353         my ($self, $reqr, $hold) = @_;
1354
1355         my $e = new_editor(xact =>1, requestor => $reqr);
1356
1357         $logger->info("reseting hold ".$hold->id);
1358
1359         my $hid = $hold->id;
1360
1361         if( $hold->capture_time and $hold->current_copy ) {
1362
1363                 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1364                         or return $e->event;
1365
1366                 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1367                         $logger->info("setting copy to status 'reshelving' on hold retarget");
1368                         $copy->status(OILS_COPY_STATUS_RESHELVING);
1369                         $copy->editor($e->requestor->id);
1370                         $copy->edit_date('now');
1371                         $e->update_asset_copy($copy) or return $e->event;
1372
1373                 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1374
1375                         # We don't want the copy to remain "in transit"
1376                         $copy->status(OILS_COPY_STATUS_RESHELVING);
1377                         $logger->warn("! reseting hold [$hid] that is in transit");
1378                         my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1379
1380                         if( $transid ) {
1381                                 my $trans = $e->retrieve_action_transit_copy($transid);
1382                                 if( $trans ) {
1383                                         $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1384                                         my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1);
1385                                         $logger->info("Transit abort completed with result $evt");
1386                                         return $evt unless "$evt" eq 1;
1387                                 }
1388                         }
1389                 }
1390         }
1391
1392         $hold->clear_capture_time;
1393         $hold->clear_current_copy;
1394         $hold->clear_shelf_time;
1395         $hold->clear_shelf_expire_time;
1396
1397         $e->update_action_hold_request($hold) or return $e->event;
1398         $e->commit;
1399
1400         $U->storagereq(
1401                 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1402
1403         return undef;
1404 }
1405
1406
1407 __PACKAGE__->register_method(
1408     method    => 'fetch_open_title_holds',
1409     api_name  => 'open-ils.circ.open_holds.retrieve',
1410     signature => q/
1411                 Returns a list ids of un-fulfilled holds for a given title id
1412                 @param authtoken The login session key
1413                 @param id the id of the item whose holds we want to retrieve
1414                 @param type The hold type - M, T, V, C
1415         /
1416 );
1417
1418 sub fetch_open_title_holds {
1419         my( $self, $conn, $auth, $id, $type, $org ) = @_;
1420         my $e = new_editor( authtoken => $auth );
1421         return $e->event unless $e->checkauth;
1422
1423         $type ||= "T";
1424         $org  ||= $e->requestor->ws_ou;
1425
1426 #       return $e->search_action_hold_request(
1427 #               { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1428
1429         # XXX make me return IDs in the future ^--
1430         my $holds = $e->search_action_hold_request(
1431                 { 
1432                         target                          => $id, 
1433                         cancel_time                     => undef, 
1434                         hold_type                       => $type, 
1435                         fulfillment_time        => undef 
1436                 }
1437         );
1438
1439         flesh_hold_transits($holds);
1440         return $holds;
1441 }
1442
1443
1444 sub flesh_hold_transits {
1445         my $holds = shift;
1446         for my $hold ( @$holds ) {
1447                 $hold->transit(
1448                         $apputils->simplereq(
1449                                 'open-ils.cstore',
1450                                 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1451                                 { hold => $hold->id },
1452                                 { order_by => { ahtc => 'id desc' }, limit => 1 }
1453                         )->[0]
1454                 );
1455         }
1456 }
1457
1458 sub flesh_hold_notices {
1459         my( $holds, $e ) = @_;
1460         $e ||= new_editor();
1461
1462         for my $hold (@$holds) {
1463                 my $notices = $e->search_action_hold_notification(
1464                         [
1465                                 { hold => $hold->id },
1466                                 { order_by => { anh => 'notify_time desc' } },
1467                         ],
1468                         {idlist=>1}
1469                 );
1470
1471                 $hold->notify_count(scalar(@$notices));
1472                 if( @$notices ) {
1473                         my $n = $e->retrieve_action_hold_notification($$notices[0])
1474                                 or return $e->event;
1475                         $hold->notify_time($n->notify_time);
1476                 }
1477         }
1478 }
1479
1480
1481 __PACKAGE__->register_method(
1482     method    => 'fetch_captured_holds',
1483     api_name  => 'open-ils.circ.captured_holds.on_shelf.retrieve',
1484     stream    => 1,
1485     signature => q/
1486                 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
1487                 @param authtoken The login session key
1488                 @param org The org id of the location in question
1489         /
1490 );
1491
1492 __PACKAGE__->register_method(
1493     method    => 'fetch_captured_holds',
1494     api_name  => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
1495     stream    => 1,
1496     signature => q/
1497                 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
1498                 @param authtoken The login session key
1499                 @param org The org id of the location in question
1500         /
1501 );
1502
1503 __PACKAGE__->register_method(
1504     method    => 'fetch_captured_holds',
1505     api_name  => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
1506     stream    => 1,
1507     signature => q/
1508                 Returns list ids of shelf-expired un-fulfilled holds for a given title id
1509                 @param authtoken The login session key
1510                 @param org The org id of the location in question
1511         /
1512 );
1513
1514
1515 sub fetch_captured_holds {
1516         my( $self, $conn, $auth, $org ) = @_;
1517
1518         my $e = new_editor(authtoken => $auth);
1519         return $e->event unless $e->checkauth;
1520         return $e->event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
1521
1522         $org ||= $e->requestor->ws_ou;
1523
1524     my $query = { 
1525         select => { ahr => ['id'] },
1526         from   => {
1527             ahr => {
1528                 acp => {
1529                     field => 'id',
1530                     fkey  => 'current_copy'
1531                 },
1532             }
1533         }, 
1534         where => {
1535             '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
1536             '+ahr' => {
1537                 capture_time     => { "!=" => undef },
1538                 current_copy     => { "!=" => undef },
1539                 fulfillment_time => undef,
1540                 pickup_lib       => $org,
1541                 cancel_time      => undef,
1542               }
1543         }
1544     };
1545     if($self->api_name =~ /expired/) {
1546         $query->{'where'}->{'+ahr'}->{'shelf_expire_time'} = {'<' => 'now'};
1547         $query->{'where'}->{'+ahr'}->{'shelf_time'} = {'!=' => undef};
1548     }
1549     my $hold_ids = $e->json_query( $query );
1550
1551     for my $hold_id (@$hold_ids) {
1552         if($self->api_name =~ /id_list/) {
1553             $conn->respond($hold_id->{id});
1554             next;
1555         } else {
1556             $conn->respond(
1557                 $e->retrieve_action_hold_request([
1558                     $hold_id->{id},
1559                     {
1560                         flesh => 1,
1561                         flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
1562                         order_by => {anh => 'notify_time desc'}
1563                     }
1564                 ])
1565             );
1566         }
1567     }
1568
1569     return undef;
1570 }
1571
1572
1573 __PACKAGE__->register_method(
1574     method    => "check_title_hold",
1575     api_name  => "open-ils.circ.title_hold.is_possible",
1576     signature => {
1577         desc  => 'Determines if a hold were to be placed by a given user, ' .
1578              'whether or not said hold would have any potential copies to fulfill it.' .
1579              'The named paramaters of the second argument include: ' .
1580              'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
1581              'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' , 
1582         params => [
1583             { desc => 'Authentication token',     type => 'string'},
1584             { desc => 'Hash of named parameters', type => 'object'},
1585         ],
1586         return => {
1587             desc => 'List of new message IDs (empty if none)',
1588             type => 'array'
1589         }
1590     }
1591 );
1592
1593 =head3 check_title_hold (token, hash)
1594
1595 The named fields in the hash are: 
1596
1597  patronid     - ID of the hold recipient  (required)
1598  depth        - hold range depth          (default 0)
1599  pickup_lib   - destination for hold, fallback value for selection_ou
1600  selection_ou - ID of org_unit establishing hard and soft hold boundary settings
1601  titleid      - ID (BRN) of the title to be held, required for Title level hold
1602  volume_id    - required for Volume level hold
1603  copy_id      - required for Copy level hold
1604  mrid         - required for Meta-record level hold
1605  hold_type    - T,C,V or M for Title, Copy, Volume or Meta-record  (default "T")
1606
1607 All key/value pairs are passed on to do_possibility_checks.
1608
1609 =cut
1610
1611 # FIXME: better params checking.  what other params are required, if any?
1612 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
1613 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still 
1614 # used in conditionals, where it may be undefined, causing a warning.
1615 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
1616
1617 sub check_title_hold {
1618     my( $self, $client, $authtoken, $params ) = @_;
1619     my $e = new_editor(authtoken=>$authtoken);
1620     return $e->event unless $e->checkauth;
1621
1622     my %params       = %$params;
1623     my $depth        = $params{depth}        || 0;
1624     my $selection_ou = $params{selection_ou} || $params{pickup_lib};
1625
1626         my $patron = $e->retrieve_actor_user($params{patronid})
1627                 or return $e->event;
1628
1629         if( $e->requestor->id ne $patron->id ) {
1630                 return $e->event unless 
1631                         $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
1632         }
1633
1634         return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
1635
1636         my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
1637                 or return $e->event;
1638
1639     my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
1640     my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
1641
1642     my @status = ();
1643     my $return_depth = $hard_boundary; # default depth to return on success
1644     if(defined $soft_boundary and $depth < $soft_boundary) {
1645         # work up the tree and as soon as we find a potential copy, use that depth
1646         # also, make sure we don't go past the hard boundary if it exists
1647
1648         # our min boundary is the greater of user-specified boundary or hard boundary
1649         my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?  
1650             $hard_boundary : $depth;
1651
1652         my $depth = $soft_boundary;
1653         while($depth >= $min_depth) {
1654             $logger->info("performing hold possibility check with soft boundary $depth");
1655             @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
1656             if ($status[0]) {
1657                 $return_depth = $depth;
1658                 last;
1659             }
1660             $depth--;
1661         }
1662     } elsif(defined $hard_boundary and $depth < $hard_boundary) {
1663         # there is no soft boundary, enforce the hard boundary if it exists
1664         $logger->info("performing hold possibility check with hard boundary $hard_boundary");
1665         @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
1666     } else {
1667         # no boundaries defined, fall back to user specifed boundary or no boundary
1668         $logger->info("performing hold possibility check with no boundary");
1669         @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
1670     }
1671
1672     if ($status[0]) {
1673         return {
1674             "success" => 1,
1675             "depth" => $return_depth,
1676             "local_avail" => $status[1]
1677         };
1678     } elsif ($status[2]) {
1679         my $n = scalar @{$status[2]};
1680         return {"success" => 0, "last_event" => $status[2]->[$n - 1]};
1681     } else {
1682         return {"success" => 0};
1683     }
1684 }
1685
1686 sub do_possibility_checks {
1687     my($e, $patron, $request_lib, $depth, %params) = @_;
1688
1689     my $titleid      = $params{titleid}      || "";
1690     my $volid        = $params{volume_id};
1691     my $copyid       = $params{copy_id};
1692     my $mrid         = $params{mrid}         || "";
1693     my $pickup_lib   = $params{pickup_lib};
1694     my $hold_type    = $params{hold_type}    || 'T';
1695     my $selection_ou = $params{selection_ou} || $pickup_lib;
1696
1697
1698         my $copy;
1699         my $volume;
1700         my $title;
1701
1702         if( $hold_type eq OILS_HOLD_TYPE_COPY ) {
1703
1704         return $e->event unless $copy   = $e->retrieve_asset_copy($copyid);
1705         return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
1706         return $e->event unless $title  = $e->retrieve_biblio_record_entry($volume->record);
1707
1708         return verify_copy_for_hold( 
1709             $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib
1710         );
1711
1712         } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
1713
1714                 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
1715                 return $e->event unless $title  = $e->retrieve_biblio_record_entry($volume->record);
1716
1717                 return _check_volume_hold_is_possible(
1718                         $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
1719         );
1720
1721         } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
1722
1723                 return _check_title_hold_is_possible(
1724                         $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
1725         );
1726
1727         } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
1728
1729                 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
1730                 my @recs = map { $_->source } @$maps;
1731                 my @status = ();
1732                 for my $rec (@recs) {
1733                         @status = _check_title_hold_is_possible(
1734                                 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
1735                         );
1736                         last if $status[1];
1737                 }
1738                 return @status;
1739         }
1740 #   else { Unrecognized hold_type ! }   # FIXME: return error? or 0?
1741 }
1742
1743 my %prox_cache;
1744 sub create_ranged_org_filter {
1745     my($e, $selection_ou, $depth) = @_;
1746
1747     # find the orgs from which this hold may be fulfilled, 
1748     # based on the selection_ou and depth
1749
1750     my $top_org = $e->search_actor_org_unit([
1751         {parent_ou => undef}, 
1752         {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
1753     my %org_filter;
1754
1755     return () if $depth == $top_org->ou_type->depth;
1756
1757     my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
1758     %org_filter = (circ_lib => []);
1759     push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
1760
1761     $logger->info("hold org filter at depth $depth and selection_ou ".
1762         "$selection_ou created list of @{$org_filter{circ_lib}}");
1763
1764     return %org_filter;
1765 }
1766
1767
1768 sub _check_title_hold_is_possible {
1769     my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
1770    
1771     my $e = new_editor();
1772     my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
1773
1774     # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
1775     my $copies = $e->json_query(
1776         { 
1777             select => { acp => ['id', 'circ_lib'] },
1778               from => {
1779                 acp => {
1780                     acn => {
1781                         field  => 'id',
1782                         fkey   => 'call_number',
1783                         'join' => {
1784                             bre => {
1785                                 field  => 'id',
1786                                 filter => { id => $titleid },
1787                                 fkey   => 'record'
1788                             }
1789                         }
1790                     },
1791                     acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
1792                     ccs  => { field => 'id', filter => { holdable => 't'}, fkey => 'status'   }
1793                 }
1794             }, 
1795             where => {
1796                 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
1797             }
1798         }
1799     );
1800
1801     $logger->info("title possible found ".scalar(@$copies)." potential copies");
1802     return (
1803         0, 0, [
1804             new OpenILS::Event(
1805                 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
1806                 "payload" => {"fail_part" => "no_ultimate_items"}
1807             )
1808         ]
1809     ) unless @$copies;
1810
1811     # -----------------------------------------------------------------------
1812     # sort the copies into buckets based on their circ_lib proximity to 
1813     # the patron's home_ou.  
1814     # -----------------------------------------------------------------------
1815
1816     my $home_org = $patron->home_ou;
1817     my $req_org = $request_lib->id;
1818
1819     $logger->info("prox cache $home_org " . $prox_cache{$home_org});
1820
1821     $prox_cache{$home_org} = 
1822         $e->search_actor_org_unit_proximity({from_org => $home_org})
1823         unless $prox_cache{$home_org};
1824     my $home_prox = $prox_cache{$home_org};
1825
1826     my %buckets;
1827     my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
1828     push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1829
1830     my @keys = sort { $a <=> $b } keys %buckets;
1831
1832
1833     if( $home_org ne $req_org ) {
1834       # -----------------------------------------------------------------------
1835       # shove the copies close to the request_lib into the primary buckets 
1836       # directly before the farthest away copies.  That way, they are not 
1837       # given priority, but they are checked before the farthest copies.
1838       # -----------------------------------------------------------------------
1839         $prox_cache{$req_org} = 
1840             $e->search_actor_org_unit_proximity({from_org => $req_org})
1841             unless $prox_cache{$req_org};
1842         my $req_prox = $prox_cache{$req_org};
1843
1844         my %buckets2;
1845         my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
1846         push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
1847
1848         my $highest_key = $keys[@keys - 1];  # the farthest prox in the exising buckets
1849         my $new_key = $highest_key - 0.5; # right before the farthest prox
1850         my @keys2   = sort { $a <=> $b } keys %buckets2;
1851         for my $key (@keys2) {
1852             last if $key >= $highest_key;
1853             push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
1854         }
1855     }
1856
1857     @keys = sort { $a <=> $b } keys %buckets;
1858
1859     my $title;
1860     my %seen;
1861     my @status;
1862     OUTER: for my $key (@keys) {
1863       my @cps = @{$buckets{$key}};
1864
1865       $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
1866
1867       for my $copyid (@cps) {
1868
1869          next if $seen{$copyid};
1870          $seen{$copyid} = 1; # there could be dupes given the merged buckets
1871          my $copy = $e->retrieve_asset_copy($copyid);
1872          $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
1873
1874          unless($title) { # grab the title if we don't already have it
1875             my $vol = $e->retrieve_asset_call_number(
1876                [ $copy->call_number, { flesh => 1, flesh_fields => { acn => ['record'] } } ] );
1877             $title = $vol->record;
1878          }
1879    
1880          @status = verify_copy_for_hold(
1881             $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
1882
1883          last OUTER if $status[0];
1884       }
1885     }
1886
1887     return @status;
1888 }
1889
1890
1891 sub _check_volume_hold_is_possible {
1892         my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
1893     my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
1894         my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
1895         $logger->info("checking possibility of volume hold for volume ".$vol->id);
1896
1897     return (
1898         0, 0, [
1899             new OpenILS::Event(
1900                 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
1901                 "payload" => {"fail_part" => "no_ultimate_items"}
1902             )
1903         ]
1904     ) unless @$copies;
1905
1906     my @status;
1907         for my $copy ( @$copies ) {
1908         @status = verify_copy_for_hold(
1909                         $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
1910         last if $status[0];
1911         }
1912         return @status;
1913 }
1914
1915
1916
1917 sub verify_copy_for_hold {
1918         my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib ) = @_;
1919         $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
1920     my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
1921                 {       patron                          => $patron, 
1922                         requestor                       => $requestor, 
1923                         copy                            => $copy,
1924                         title                           => $title, 
1925                         title_descriptor        => $title->fixed_fields, # this is fleshed into the title object
1926                         pickup_lib                      => $pickup_lib,
1927                         request_lib                     => $request_lib,
1928             new_hold            => 1,
1929             show_event_list     => 1
1930                 } 
1931         );
1932
1933     return (
1934         (not scalar @$permitted), # true if permitted is an empty arrayref
1935         (
1936                 ($copy->circ_lib == $pickup_lib) and 
1937             ($copy->status == OILS_COPY_STATUS_AVAILABLE)
1938         ),
1939         $permitted
1940     );
1941 }
1942
1943
1944
1945 sub find_nearest_permitted_hold {
1946
1947     my $class  = shift;
1948     my $editor = shift;     # CStoreEditor object
1949     my $copy   = shift;     # copy to target
1950     my $user   = shift;     # staff
1951     my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
1952       
1953     my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
1954
1955     my $bc = $copy->barcode;
1956
1957         # find any existing holds that already target this copy
1958         my $old_holds = $editor->search_action_hold_request(
1959                 {       current_copy => $copy->id, 
1960                         cancel_time  => undef, 
1961                         capture_time => undef 
1962                 } 
1963         );
1964
1965         # hold->type "R" means we need this copy
1966         for my $h (@$old_holds) { return ($h) if $h->hold_type eq 'R'; }
1967
1968
1969     my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
1970
1971         $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
1972         " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
1973
1974         # search for what should be the best holds for this copy to fulfill
1975         my $best_holds = $U->storagereq(
1976         "open-ils.storage.action.hold_request.nearest_hold.atomic", 
1977                 $user->ws_ou, $copy->id, 10, $hold_stall_interval );
1978
1979         unless(@$best_holds) {
1980
1981                 if( my $hold = $$old_holds[0] ) {
1982                         $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
1983                         return ($hold);
1984                 }
1985
1986                 $logger->info("circulator: no suitable holds found for copy $bc");
1987                 return (undef, $evt);
1988         }
1989
1990
1991         my $best_hold;
1992
1993         # for each potential hold, we have to run the permit script
1994         # to make sure the hold is actually permitted.
1995         for my $holdid (@$best_holds) {
1996                 next unless $holdid;
1997                 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
1998
1999                 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
2000                 my $reqr = $editor->retrieve_actor_user($hold->requestor) or next;
2001                 my $rlib = $editor->retrieve_actor_org_unit($hold->request_lib) or next;
2002
2003                 # see if this hold is permitted
2004                 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2005                         {       patron_id                       => $hold->usr,
2006                                 requestor                       => $reqr,
2007                                 copy                            => $copy,
2008                                 pickup_lib                      => $hold->pickup_lib,
2009                                 request_lib                     => $rlib,
2010                         } 
2011                 );
2012
2013                 if( $permitted ) {
2014                         $best_hold = $hold;
2015                         last;
2016                 }
2017         }
2018
2019
2020         unless( $best_hold ) { # no "good" permitted holds were found
2021                 if( my $hold = $$old_holds[0] ) { # can we return a pre-targeted hold?
2022                         $logger->info("circulator: using existing pre-targeted hold ".$hold->id." in hold search");
2023                         return ($hold);
2024                 }
2025
2026                 # we got nuthin
2027                 $logger->info("circulator: no suitable holds found for copy $bc");
2028                 return (undef, $evt);
2029         }
2030
2031         $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
2032
2033         # indicate a permitted hold was found
2034         return $best_hold if $check_only;
2035
2036         # we've found a permitted hold.  we need to "grab" the copy 
2037         # to prevent re-targeted holds (next part) from re-grabbing the copy
2038         $best_hold->current_copy($copy->id);
2039         $editor->update_action_hold_request($best_hold) 
2040                 or return (undef, $editor->event);
2041
2042
2043     my @retarget;
2044
2045         # re-target any other holds that already target this copy
2046         for my $old_hold (@$old_holds) {
2047                 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
2048                 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
2049             $old_hold->id." after a better hold [".$best_hold->id."] was found");
2050         $old_hold->clear_current_copy;
2051         $old_hold->clear_prev_check_time;
2052         $editor->update_action_hold_request($old_hold) 
2053             or return (undef, $editor->event);
2054         push(@retarget, $old_hold->id);
2055         }
2056
2057         return ($best_hold, undef, (@retarget) ? \@retarget : undef);
2058 }
2059
2060
2061
2062
2063
2064
2065 __PACKAGE__->register_method(
2066     method   => 'all_rec_holds',
2067     api_name => 'open-ils.circ.holds.retrieve_all_from_title',
2068 );
2069
2070 sub all_rec_holds {
2071         my( $self, $conn, $auth, $title_id, $args ) = @_;
2072
2073         my $e = new_editor(authtoken=>$auth);
2074         $e->checkauth or return $e->event;
2075         $e->allowed('VIEW_HOLD') or return $e->event;
2076
2077         $args ||= {};
2078     $args->{fulfillment_time} = undef; #  we don't want to see old fulfilled holds
2079         $args->{cancel_time} = undef;
2080
2081         my $resp = { volume_holds => [], copy_holds => [], metarecord_holds => [] };
2082
2083     my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
2084     if($mr_map) {
2085         $resp->{metarecord_holds} = $e->search_action_hold_request(
2086             {   hold_type => OILS_HOLD_TYPE_METARECORD,
2087                 target => $mr_map->metarecord,
2088                 %$args 
2089             }, {idlist => 1}
2090         );
2091     }
2092
2093         $resp->{title_holds} = $e->search_action_hold_request(
2094                 { 
2095                         hold_type => OILS_HOLD_TYPE_TITLE, 
2096                         target => $title_id, 
2097                         %$args 
2098                 }, {idlist=>1} );
2099
2100         my $vols = $e->search_asset_call_number(
2101                 { record => $title_id, deleted => 'f' }, {idlist=>1});
2102
2103         return $resp unless @$vols;
2104
2105         $resp->{volume_holds} = $e->search_action_hold_request(
2106                 { 
2107                         hold_type => OILS_HOLD_TYPE_VOLUME, 
2108                         target => $vols,
2109                         %$args }, 
2110                 {idlist=>1} );
2111
2112         my $copies = $e->search_asset_copy(
2113                 { call_number => $vols, deleted => 'f' }, {idlist=>1});
2114
2115         return $resp unless @$copies;
2116
2117         $resp->{copy_holds} = $e->search_action_hold_request(
2118                 { 
2119                         hold_type => OILS_HOLD_TYPE_COPY,
2120                         target => $copies,
2121                         %$args }, 
2122                 {idlist=>1} );
2123
2124         return $resp;
2125 }
2126
2127
2128
2129
2130
2131 __PACKAGE__->register_method(
2132     method        => 'uber_hold',
2133     authoritative => 1,
2134     api_name      => 'open-ils.circ.hold.details.retrieve'
2135 );
2136
2137 sub uber_hold {
2138         my($self, $client, $auth, $hold_id) = @_;
2139         my $e = new_editor(authtoken=>$auth);
2140         $e->checkauth or return $e->event;
2141     return uber_hold_impl($e, $hold_id);
2142 }
2143
2144 __PACKAGE__->register_method(
2145     method        => 'batch_uber_hold',
2146     authoritative => 1,
2147     stream        => 1,
2148     api_name      => 'open-ils.circ.hold.details.batch.retrieve'
2149 );
2150
2151 sub batch_uber_hold {
2152         my($self, $client, $auth, $hold_ids) = @_;
2153         my $e = new_editor(authtoken=>$auth);
2154         $e->checkauth or return $e->event;
2155     $client->respond(uber_hold_impl($e, $_)) for @$hold_ids;
2156     return undef;
2157 }
2158
2159 sub uber_hold_impl {
2160     my($e, $hold_id) = @_;
2161
2162         my $resp = {};
2163
2164         my $hold = $e->retrieve_action_hold_request(
2165                 [
2166                         $hold_id,
2167                         {
2168                                 flesh => 1,
2169                                 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
2170                         }
2171                 ]
2172         ) or return $e->event;
2173
2174     if($hold->usr->id ne $e->requestor->id) {
2175         # A user is allowed to see his/her own holds
2176             $e->allowed('VIEW_HOLD') or return $e->event;
2177         $hold->notes( # filter out any non-staff ("private") notes
2178             [ grep { !$U->is_true($_->staff) } @{$hold->notes} ] );
2179
2180     } else {
2181         # caller is asking for own hold, but may not have permission to view staff notes
2182             unless($e->allowed('VIEW_HOLD')) {
2183             $hold->notes( # filter out any staff notes
2184                 [ grep { $U->is_true($_->staff) } @{$hold->notes} ] );
2185         }
2186     }
2187
2188         my $user = $hold->usr;
2189         $hold->usr($user->id);
2190
2191         my $card = $e->retrieve_actor_card($user->card)
2192                 or return $e->event;
2193
2194         my( $mvr, $volume, $copy ) = find_hold_mvr($e, $hold);
2195
2196         flesh_hold_notices([$hold], $e);
2197         flesh_hold_transits([$hold]);
2198
2199     my $details = retrieve_hold_queue_status_impl($e, $hold);
2200
2201     return {
2202         hold           => $hold,
2203         copy           => $copy,
2204         volume         => $volume,
2205         mvr            => $mvr,
2206         patron_first   => $user->first_given_name,
2207         patron_last    => $user->family_name,
2208         patron_barcode => $card->barcode,
2209         %$details
2210     };
2211 }
2212
2213
2214
2215 # -----------------------------------------------------
2216 # Returns the MVR object that represents what the
2217 # hold is all about
2218 # -----------------------------------------------------
2219 sub find_hold_mvr {
2220         my( $e, $hold ) = @_;
2221
2222         my $tid;
2223         my $copy;
2224         my $volume;
2225
2226         if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2227                 my $mr = $e->retrieve_metabib_metarecord($hold->target)
2228                         or return $e->event;
2229                 $tid = $mr->master_record;
2230
2231         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
2232                 $tid = $hold->target;
2233
2234         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2235                 $volume = $e->retrieve_asset_call_number($hold->target)
2236                         or return $e->event;
2237                 $tid = $volume->record;
2238
2239         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_COPY ) {
2240                 $copy = $e->retrieve_asset_copy($hold->target)
2241                         or return $e->event;
2242                 $volume = $e->retrieve_asset_call_number($copy->call_number)
2243                         or return $e->event;
2244                 $tid = $volume->record;
2245         }
2246
2247         if(!$copy and ref $hold->current_copy ) {
2248                 $copy = $hold->current_copy;
2249                 $hold->current_copy($copy->id);
2250         }
2251
2252         if(!$volume and $copy) {
2253                 $volume = $e->retrieve_asset_call_number($copy->call_number);
2254         }
2255
2256     # TODO return metarcord mvr for M holds
2257         my $title = $e->retrieve_biblio_record_entry($tid);
2258         return ( $U->record_to_mvr($title), $volume, $copy );
2259 }
2260
2261
2262 __PACKAGE__->register_method(
2263     method    => 'clear_shelf_process',
2264     stream    => 1,
2265     api_name  => 'open-ils.circ.hold.clear_shelf.process',
2266     signature => {
2267         desc => q/
2268             1. Find all holds that have expired on the holds shelf
2269             2. Cancel the holds
2270             3. If a clear-shelf status is configured, put targeted copies into this status
2271             4. Divide copies into 3 groups: items to transit, items to reshelve, and items
2272                 that are needed for holds.  No subsequent action is taken on the holds
2273                 or items after grouping.
2274         /
2275     }
2276 );
2277
2278 sub clear_shelf_process {
2279         my($self, $client, $auth, $org_id) = @_;
2280
2281         my $e = new_editor(authtoken=>$auth, xact => 1);
2282         $e->checkauth or return $e->die_event;
2283
2284     $org_id ||= $e->requestor->ws_ou;
2285         $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
2286
2287     my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
2288
2289     # Find holds on the shelf that have been there too long
2290     my $hold_ids = $e->search_action_hold_request(
2291         {   shelf_expire_time => {'<' => 'now'},
2292             pickup_lib        => $org_id,
2293             cancel_time       => undef,
2294             fulfillment_time  => undef,
2295             shelf_time        => {'!=' => undef}
2296         },
2297         { idlist => 1 }
2298     );
2299
2300
2301     my @holds;
2302     for my $hold_id (@$hold_ids) {
2303
2304         $logger->info("Clear shelf processing hold $hold_id");
2305         
2306         my $hold = $e->retrieve_action_hold_request([
2307             $hold_id, {   
2308                 flesh => 1,
2309                 flesh_fields => {ahr => ['current_copy']}
2310             }
2311         ]);
2312
2313         $hold->cancel_time('now');
2314         $hold->cancel_cause(2); # Hold Shelf expiration
2315         $e->update_action_hold_request($hold) or return $e->die_event;
2316
2317         my $copy = $hold->current_copy;
2318
2319         if($copy_status or $copy_status == 0) {
2320             # if a clear-shelf copy status is defined, update the copy
2321             $copy->status($copy_status);
2322             $copy->edit_date('now');
2323             $copy->editor($e->requestor->id);
2324             $e->update_asset_copy($copy) or return $e->die_event;
2325         }
2326
2327         push(@holds, $hold);
2328     }
2329
2330     if ($e->commit) {
2331
2332         for my $hold (@holds) {
2333
2334             my $copy = $hold->current_copy;
2335
2336             my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
2337
2338             if($alt_hold) {
2339
2340                 # copy is needed for a hold
2341                 $client->respond({action => 'hold', copy => $copy, hold_id => $hold->id});
2342
2343             } elsif($copy->circ_lib != $e->requestor->ws_ou) {
2344
2345                 # copy needs to transit
2346                 $client->respond({action => 'transit', copy => $copy, hold_id => $hold->id});
2347
2348             } else {
2349
2350                 # copy needs to go back to the shelf
2351                 $client->respond({action => 'shelf', copy => $copy, hold_id => $hold->id});
2352             }
2353         }
2354
2355         # tell the client we're done
2356         $client->respond_complete;
2357
2358         # fire off the hold cancelation trigger
2359         my $trigger = OpenSRF::AppSession->connect('open-ils.trigger');
2360
2361         for my $hold (@holds) {
2362
2363             my $req = $trigger->request(
2364                 'open-ils.trigger.event.autocreate', 
2365                 'hold_request.cancel.expire_holds_shelf', 
2366                 $hold, $org_id);
2367
2368             # wait for response so don't flood the service
2369             $req->recv;
2370         }
2371
2372         $trigger->disconnect;
2373
2374     } else {
2375         # tell the client we're done
2376         $client->respond_complete;
2377     }
2378 }
2379
2380 __PACKAGE__->register_method(
2381     method    => 'usr_hold_summary',
2382     api_name  => 'open-ils.circ.holds.user_summary',
2383     signature => q/
2384         Returns a summary of holds statuses for a given user
2385     /
2386 );
2387
2388 sub usr_hold_summary {
2389     my($self, $conn, $auth, $user_id) = @_;
2390
2391         my $e = new_editor(authtoken=>$auth);
2392         $e->checkauth or return $e->event;
2393         $e->allowed('VIEW_HOLD') or return $e->event;
2394
2395     my $holds = $e->search_action_hold_request(
2396         {  
2397             usr =>  $user_id , 
2398             fulfillment_time => undef,
2399             cancel_time      => undef,
2400         }
2401     );
2402
2403     my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
2404     $summary{_hold_status($e, $_)} += 1 for @$holds;
2405     return \%summary;
2406 }
2407
2408
2409
2410 __PACKAGE__->register_method(
2411     method    => 'hold_has_copy_at',
2412     api_name  => 'open-ils.circ.hold.has_copy_at',
2413     signature => {
2414         desc   => 
2415                 'Returns the ID of the found copy and name of the shelving location if there is ' .
2416                 'an available copy at the specified org unit.  Returns empty hash otherwise.  '   .
2417                 'The anticipated use for this method is to determine whether an item is '         .
2418                 'available at the library where the user is placing the hold (or, alternatively, '.
2419                 'at the pickup library) to encourage bypassing the hold placement and just '      .
2420                 'checking out the item.' ,
2421         params => {
2422             { desc => 'Authentication Token', type => 'string' },
2423             { desc => 'Method Arguments.  Options include: hold_type, hold_target, org_unit.  ' 
2424                     . 'hold_type is the hold type code (T, V, C, M, ...).  '
2425                     . 'hold_target is the identifier of the hold target object.  ' 
2426                     . 'org_unit is org unit ID.', 
2427               type => 'object' 
2428             },
2429         },
2430         return => { 
2431             desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
2432             type => 'object' 
2433         }
2434     }
2435 );
2436
2437 sub hold_has_copy_at {
2438     my($self, $conn, $auth, $args) = @_;
2439
2440         my $e = new_editor(authtoken=>$auth);
2441         $e->checkauth or return $e->event;
2442
2443     my $hold_type   = $$args{hold_type};
2444     my $hold_target = $$args{hold_target};
2445     my $org_unit    = $$args{org_unit};
2446
2447     my $query = {
2448         select => {acp => ['id'], acpl => ['name']},
2449         from   => {
2450             acp => {
2451                 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
2452                 ccs  => {field => 'id', filter => { holdable => 't'}, fkey => 'status'  }
2453             }
2454         },
2455         where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit}},
2456         limit => 1
2457     };
2458
2459     if($hold_type eq 'C') {
2460
2461         $query->{where}->{'+acp'}->{id} = $hold_target;
2462
2463     } elsif($hold_type eq 'V') {
2464
2465         $query->{where}->{'+acp'}->{call_number} = $hold_target;
2466     
2467     } elsif($hold_type eq 'T') {
2468
2469         $query->{from}->{acp}->{acn} = {
2470             field  => 'id',
2471             fkey   => 'call_number',
2472             'join' => {
2473                 bre => {
2474                     field  => 'id',
2475                     filter => {id => $hold_target},
2476                     fkey   => 'record'
2477                 }
2478             }
2479         };
2480
2481     } else {
2482
2483         $query->{from}->{acp}->{acn} = {
2484             field => 'id',
2485             fkey  => 'call_number',
2486             join  => {
2487                 bre => {
2488                     field => 'id',
2489                     fkey  => 'record',
2490                     join  => {
2491                         mmrsm => {
2492                             field  => 'source',
2493                             fkey   => 'id',
2494                             filter => {metarecord => $hold_target},
2495                         }
2496                     }
2497                 }
2498             }
2499         };
2500     }
2501
2502     my $res = $e->json_query($query)->[0] or return {};
2503     return {copy => $res->{id}, location => $res->{name}} if $res;
2504 }
2505
2506
2507 # returns true if the user already has an item checked out 
2508 # that could be used to fulfill the requested hold.
2509 sub hold_item_is_checked_out {
2510     my($e, $user_id, $hold_type, $hold_target) = @_;
2511
2512     my $query = {
2513         select => {acp => ['id']},
2514         from   => {acp => {}},
2515         where  => {
2516             '+acp' => {
2517                 id => {
2518                     in => { # copies for circs the user has checked out
2519                         select => {circ => ['target_copy']},
2520                         from   => 'circ',
2521                         where  => {
2522                             usr => $user_id,
2523                             checkin_time => undef,
2524                             '-or' => [
2525                                 {stop_fines => ["MAXFINES","LONGOVERDUE"]},
2526                                 {stop_fines => undef}
2527                             ],
2528                         }
2529                     }
2530                 }
2531             }
2532         },
2533         limit => 1
2534     };
2535
2536     if($hold_type eq 'C') {
2537
2538         $query->{where}->{'+acp'}->{id}->{in}->{where}->{'target_copy'} = $hold_target;
2539
2540     } elsif($hold_type eq 'V') {
2541
2542         $query->{where}->{'+acp'}->{call_number} = $hold_target;
2543     
2544     } elsif($hold_type eq 'T') {
2545
2546         $query->{from}->{acp}->{acn} = {
2547             field  => 'id',
2548             fkey   => 'call_number',
2549             'join' => {
2550                 bre => {
2551                     field  => 'id',
2552                     filter => {id => $hold_target},
2553                     fkey   => 'record'
2554                 }
2555             }
2556         };
2557
2558     } else {
2559
2560         $query->{from}->{acp}->{acn} = {
2561             field => 'id',
2562             fkey => 'call_number',
2563             join => {
2564                 bre => {
2565                     field => 'id',
2566                     fkey => 'record',
2567                     join => {
2568                         mmrsm => {
2569                             field => 'source',
2570                             fkey => 'id',
2571                             filter => {metarecord => $hold_target},
2572                         }
2573                     }
2574                 }
2575             }
2576         };
2577     }
2578
2579     return $e->json_query($query)->[0];
2580 }
2581
2582 __PACKAGE__->register_method(
2583     method    => 'change_hold_title',
2584     api_name  => 'open-ils.circ.hold.change_title',
2585     signature => {
2586         desc => q/
2587             Updates all title level holds targeting the specified bibs to point a new bib./,
2588         params => [
2589             { desc => 'Authentication Token', type => 'string' },
2590             { desc => 'New Target Bib Id',    type => 'number' },
2591             { desc => 'Old Target Bib Ids',   type => 'array'  },
2592         ],
2593         return => { desc => '1 on success' }
2594     }
2595 );
2596
2597 sub change_hold_title {
2598     my( $self, $client, $auth, $new_bib_id, $bib_ids ) = @_;
2599
2600     my $e = new_editor(authtoken=>$auth, xact=>1);
2601     return $e->event unless $e->checkauth;
2602
2603     my $holds = $e->search_action_hold_request(
2604         [
2605             {
2606                 cancel_time      => undef,
2607                 fulfillment_time => undef,
2608                 hold_type        => 'T',
2609                 target           => $bib_ids
2610             },
2611             {
2612                 flesh        => 1,
2613                 flesh_fields => { ahr => ['usr'] }
2614             }
2615         ],
2616         { substream => 1 }
2617     );
2618
2619     for my $hold (@$holds) {
2620         $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
2621         $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
2622         $hold->target( $new_bib_id );
2623         $e->update_action_hold_request($hold) or return $e->die_event;
2624     }
2625
2626     $e->commit;
2627
2628     return 1;
2629 }
2630
2631
2632 __PACKAGE__->register_method(
2633     method    => 'rec_hold_count',
2634     api_name  => 'open-ils.circ.bre.holds.count',
2635     signature => {
2636         desc => q/Returns the total number of holds that target the 
2637             selected bib record or its associated copies and call_numbers/,
2638         params => [
2639             { desc => 'Bib ID', type => 'number' },
2640         ],
2641         return => {desc => 'Hold count', type => 'number'}
2642     }
2643 );
2644
2645 __PACKAGE__->register_method(
2646     method    => 'rec_hold_count',
2647     api_name  => 'open-ils.circ.mmr.holds.count',
2648     signature => {
2649         desc => q/Returns the total number of holds that target the 
2650             selected metarecord or its associated copies, call_numbers, and bib records/,
2651         params => [
2652             { desc => 'Metarecord ID', type => 'number' },
2653         ],
2654         return => {desc => 'Hold count', type => 'number'}
2655     }
2656 );
2657
2658 sub rec_hold_count {
2659     my($self, $conn, $target_id) = @_;
2660
2661
2662     my $mmr_join = {
2663         mmrsm => {
2664             field => 'id',
2665             fkey => 'source',
2666             filter => {metarecord => $target_id}
2667         }
2668     };
2669
2670     my $bre_join = {
2671         bre => {
2672             field => 'id',
2673             filter => { id => $target_id },
2674             fkey => 'record'
2675         }
2676     };
2677
2678     if($self->api_name =~ /mmr/) {
2679         delete $bre_join->{bre}->{filter};
2680         $bre_join->{bre}->{join} = $mmr_join;
2681     }
2682
2683     my $cn_join = {
2684         acn => {
2685             field => 'id',
2686             fkey => 'call_number',
2687             join => $bre_join
2688         }
2689     };
2690
2691     my $query = {
2692         select => {ahr => [{column => 'id', transform => 'count', alias => 'count'}]},
2693         from => 'ahr',
2694         where => {
2695             '+ahr' => {
2696                 cancel_time => undef, 
2697                 fulfillment_time => undef,
2698                 '-or' => [
2699                     {
2700                         '-and' => {
2701                             hold_type => 'C',
2702                             target => {
2703                                 in => {
2704                                     select => {acp => ['id']},
2705                                     from => { acp => $cn_join }
2706                                 }
2707                             }
2708                         }
2709                     },
2710                     {
2711                         '-and' => {
2712                             hold_type => 'V',
2713                             target => {
2714                                 in => {
2715                                     select => {acn => ['id']},
2716                                     from => {acn => $bre_join}
2717                                 }
2718                             }
2719                         }
2720                     },
2721                     {
2722                         '-and' => {
2723                             hold_type => 'T',
2724                             target => $target_id
2725                         }
2726                     }
2727                 ]
2728             }
2729         }
2730     };
2731
2732     if($self->api_name =~ /mmr/) {
2733         $query->{where}->{'+ahr'}->{'-or'}->[2] = {
2734             '-and' => {
2735                 hold_type => 'T',
2736                 target => {
2737                     in => {
2738                         select => {bre => ['id']},
2739                         from => {bre => $mmr_join}
2740                     }
2741                 }
2742             }
2743         };
2744
2745         $query->{where}->{'+ahr'}->{'-or'}->[3] = {
2746             '-and' => {
2747                 hold_type => 'M',
2748                 target => $target_id
2749             }
2750         };
2751     }
2752
2753
2754     return new_editor()->json_query($query)->[0]->{count};
2755 }
2756
2757
2758
2759
2760
2761
2762 1;