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