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