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