]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Circ/Holds.pm
Nearest Hold: Look at 100 instead of 10 holds
[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     my $need_retarget = 0;
887
888     unless($hold) {
889         $hold = $e->retrieve_action_hold_request($values->{id})
890             or return $e->die_event;
891         for my $k (keys %$values) {
892             # Outside of pickup_lib (covered by the first regex) I don't know when these would currently change.
893             # But hey, why not cover things that may happen later?
894             if ($k =~ '_(lib|ou)$' || $k eq 'target' || $k eq 'hold_type' || $k eq 'requestor' || $k eq 'selection_depth' || $k eq 'holdable_formats') {
895                 if (defined $values->{$k} && defined $hold->$k() && $values->{$k} ne $hold->$k()) {
896                     # Value changed? RETARGET!
897                     $need_retarget = 1;
898                 } elsif (defined $hold->$k() != defined $values->{$k}) {
899                     # Value being set or cleared? RETARGET!
900                     $need_retarget = 1;
901                 }
902             }
903             if (defined $values->{$k}) {
904                 $hold->$k($values->{$k});
905             } else {
906                 my $f = "clear_$k"; $hold->$f();
907             }
908         }
909     }
910
911     my $orig_hold = $e->retrieve_action_hold_request($hold->id)
912         or return $e->die_event;
913
914     # don't allow the user to be changed
915     return OpenILS::Event->new('BAD_PARAMS') if $hold->usr != $orig_hold->usr;
916
917     if($hold->usr ne $e->requestor->id) {
918         # if the hold is for a different user, make sure the 
919         # requestor has the appropriate permissions
920         my $usr = $e->retrieve_actor_user($hold->usr)
921             or return $e->die_event;
922         return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
923     }
924
925
926     # --------------------------------------------------------------
927     # Changing the request time is like playing God
928     # --------------------------------------------------------------
929     if($hold->request_time ne $orig_hold->request_time) {
930         return OpenILS::Event->new('BAD_PARAMS') if $hold->fulfillment_time;
931         return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
932     }
933     
934         
935         # --------------------------------------------------------------
936         # Code for making sure staff have appropriate permissons for cut_in_line
937         # This, as is, doesn't prevent a user from cutting their own holds in line 
938         # but needs to
939         # --------------------------------------------------------------        
940         if($U->is_true($hold->cut_in_line) ne $U->is_true($orig_hold->cut_in_line)) {
941                 return $e->die_event unless $e->allowed('UPDATE_HOLD_REQUEST_TIME', $hold->pickup_lib);
942         }
943
944
945     # --------------------------------------------------------------
946     # Disallow hold suspencion if the hold is already captured.
947     # --------------------------------------------------------------
948     if ($U->is_true($hold->frozen) and not $U->is_true($orig_hold->frozen)) {
949         $hold_status = _hold_status($e, $hold);
950         if ($hold_status > 2 && $hold_status != 7) { # hold is captured
951             $logger->info("bypassing hold freeze on captured hold");
952             return OpenILS::Event->new('HOLD_SUSPEND_AFTER_CAPTURE');
953         }
954     }
955
956
957     # --------------------------------------------------------------
958     # if the hold is on the holds shelf or in transit and the pickup 
959     # lib changes we need to create a new transit.
960     # --------------------------------------------------------------
961     if($orig_hold->pickup_lib ne $hold->pickup_lib) {
962
963         $hold_status = _hold_status($e, $hold) unless $hold_status;
964
965         if($hold_status == 3) { # in transit
966
967             return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $orig_hold->pickup_lib);
968             return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_TRANSIT', $hold->pickup_lib);
969
970             $logger->info("updating pickup lib for hold ".$hold->id." while already in transit");
971
972             # update the transit to reflect the new pickup location
973                         my $transit = $e->search_action_hold_transit_copy(
974                 {hold=>$hold->id, dest_recv_time => undef})->[0] 
975                 or return $e->die_event;
976
977             $transit->prev_dest($transit->dest); # mark the previous destination on the transit
978             $transit->dest($hold->pickup_lib);
979             $e->update_action_hold_transit_copy($transit) or return $e->die_event;
980
981         } elsif($hold_status == 4 or $hold_status == 5 or $hold_status == 8) { # on holds shelf
982
983             return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $orig_hold->pickup_lib);
984             return $e->die_event unless $e->allowed('UPDATE_PICKUP_LIB_FROM_HOLDS_SHELF', $hold->pickup_lib);
985
986             $logger->info("updating pickup lib for hold ".$hold->id." while on holds shelf");
987
988             if ($hold->pickup_lib eq $orig_hold->current_shelf_lib) {
989                 # This can happen if the pickup lib is changed while the hold is 
990                 # on the shelf, then changed back to the original pickup lib.
991                 # Restore the original shelf_expire_time to prevent abuse.
992                 set_hold_shelf_expire_time(undef, $hold, $e, $hold->shelf_time);
993
994             } else {
995                 # clear to prevent premature shelf expiration
996                 $hold->clear_shelf_expire_time;
997             }
998         }
999     } 
1000
1001     update_hold_if_frozen($self, $e, $hold, $orig_hold);
1002     $e->update_action_hold_request($hold) or return $e->die_event;
1003     $e->commit;
1004
1005     # a change to mint-condition changes the set of potential copies, so retarget the hold;
1006     if($U->is_true($hold->mint_condition) and !$U->is_true($orig_hold->mint_condition)) {
1007         _reset_hold($self, $e->requestor, $hold) 
1008     } elsif($need_retarget && !defined $hold->capture_time()) { # If needed, retarget the hold due to changes
1009         $U->storagereq(
1010                 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1011     }
1012
1013     return $hold->id;
1014 }
1015
1016 # this does not update the hold in the DB.  It only 
1017 # sets the shelf_expire_time field on the hold object.
1018 # start_time is optional and defaults to 'now'
1019 sub set_hold_shelf_expire_time {
1020     my ($class, $hold, $editor, $start_time) = @_;
1021
1022     my $shelf_expire = $U->ou_ancestor_setting_value( 
1023         $hold->pickup_lib,
1024         'circ.holds.default_shelf_expire_interval', 
1025         $editor
1026     );
1027
1028     return undef unless $shelf_expire;
1029
1030     $start_time = ($start_time) ? 
1031         DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time)) :
1032         DateTime->now;
1033
1034     my $seconds = OpenSRF::Utils->interval_to_seconds($shelf_expire);
1035     my $expire_time = $start_time->add(seconds => $seconds);
1036
1037     # if the shelf expire time overlaps with a pickup lib's 
1038     # closed date, push it out to the first open date
1039     my $dateinfo = $U->storagereq(
1040         'open-ils.storage.actor.org_unit.closed_date.overlap', 
1041         $hold->pickup_lib, $expire_time->strftime('%FT%T%z'));
1042
1043     if($dateinfo) {
1044         my $dt_parser = DateTime::Format::ISO8601->new;
1045         $expire_time = $dt_parser->parse_datetime(cleanse_ISO8601($dateinfo->{end}));
1046
1047         # TODO: enable/disable time bump via setting?
1048         $expire_time->set(hour => '23', minute => '59', second => '59');
1049
1050         $logger->info("circulator: shelf_expire_time overlaps".
1051             " with closed date, pushing expire time to $expire_time");
1052     }
1053
1054     $hold->shelf_expire_time($expire_time->strftime('%FT%T%z'));
1055     return undef;
1056 }
1057
1058
1059 sub transit_hold {
1060     my($e, $orig_hold, $hold, $copy) = @_;
1061     my $src  = $orig_hold->pickup_lib;
1062     my $dest = $hold->pickup_lib;
1063
1064     $logger->info("putting hold into transit on pickup_lib update");
1065
1066     my $transit = Fieldmapper::action::hold_transit_copy->new;
1067     $transit->hold($hold->id);
1068     $transit->source($src);
1069     $transit->dest($dest);
1070     $transit->target_copy($copy->id);
1071     $transit->source_send_time('now');
1072     $transit->copy_status(OILS_COPY_STATUS_ON_HOLDS_SHELF);
1073
1074     $copy->status(OILS_COPY_STATUS_IN_TRANSIT);
1075     $copy->editor($e->requestor->id);
1076     $copy->edit_date('now');
1077
1078     $e->create_action_hold_transit_copy($transit) or return $e->die_event;
1079     $e->update_asset_copy($copy) or return $e->die_event;
1080     return undef;
1081 }
1082
1083 # if the hold is frozen, this method ensures that the hold is not "targeted", 
1084 # that is, it clears the current_copy and prev_check_time to essentiallly 
1085 # reset the hold.  If it is being activated, it runs the targeter in the background
1086 sub update_hold_if_frozen {
1087     my($self, $e, $hold, $orig_hold) = @_;
1088     return if $hold->capture_time;
1089
1090     if($U->is_true($hold->frozen)) {
1091         $logger->info("clearing current_copy and check_time for frozen hold ".$hold->id);
1092         $hold->clear_current_copy;
1093         $hold->clear_prev_check_time;
1094
1095     } else {
1096         if($U->is_true($orig_hold->frozen)) {
1097             $logger->info("Running targeter on activated hold ".$hold->id);
1098             $U->storagereq( 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1099         }
1100     }
1101 }
1102
1103 __PACKAGE__->register_method(
1104     method    => "hold_note_CUD",
1105     api_name  => "open-ils.circ.hold_request.note.cud",
1106     signature => {
1107         desc   => 'Create, update or delete a hold request note.  If the operator (from Auth. token) '
1108                 . 'is not the owner of the hold, the UPDATE_HOLD permission is required',
1109         params => [
1110             { desc => 'Authentication token', type => 'string' },
1111             { desc => 'Hold note object',     type => 'object' }
1112         ],
1113         return => {
1114             desc => 'Returns the note ID, event on error'
1115         },
1116     }
1117 );
1118
1119 sub hold_note_CUD {
1120         my($self, $conn, $auth, $note) = @_;
1121
1122     my $e = new_editor(authtoken => $auth, xact => 1);
1123     return $e->die_event unless $e->checkauth;
1124
1125     my $hold = $e->retrieve_action_hold_request($note->hold)
1126         or return $e->die_event;
1127
1128     if($hold->usr ne $e->requestor->id) {
1129         my $usr = $e->retrieve_actor_user($hold->usr);
1130         return $e->die_event unless $e->allowed('UPDATE_HOLD', $usr->home_ou);
1131         $note->staff('t') if $note->isnew;
1132     }
1133
1134     if($note->isnew) {
1135         $e->create_action_hold_request_note($note) or return $e->die_event;
1136     } elsif($note->ischanged) {
1137         $e->update_action_hold_request_note($note) or return $e->die_event;
1138     } elsif($note->isdeleted) {
1139         $e->delete_action_hold_request_note($note) or return $e->die_event;
1140     }
1141
1142     $e->commit;
1143     return $note->id;
1144 }
1145
1146
1147 __PACKAGE__->register_method(
1148     method    => "retrieve_hold_status",
1149     api_name  => "open-ils.circ.hold.status.retrieve",
1150     signature => {
1151         desc   => 'Calculates the current status of the hold. The requestor must have '      .
1152                   'VIEW_HOLD permissions if the hold is for a user other than the requestor' ,
1153         param  => [
1154             { desc => 'Hold ID', type => 'number' }
1155         ],
1156         return => {
1157             # type => 'number',     # event sometimes
1158             desc => <<'END_OF_DESC'
1159 Returns event on error or:
1160 -1 on error (for now),
1161  1 for 'waiting for copy to become available',
1162  2 for 'waiting for copy capture',
1163  3 for 'in transit',
1164  4 for 'arrived',
1165  5 for 'hold-shelf-delay'
1166  6 for 'canceled'
1167  7 for 'suspended'
1168  8 for 'captured, on wrong hold shelf'
1169 END_OF_DESC
1170         }
1171     }
1172 );
1173
1174 sub retrieve_hold_status {
1175         my($self, $client, $auth, $hold_id) = @_;
1176
1177         my $e = new_editor(authtoken => $auth);
1178         return $e->event unless $e->checkauth;
1179         my $hold = $e->retrieve_action_hold_request($hold_id)
1180                 or return $e->event;
1181
1182         if( $e->requestor->id != $hold->usr ) {
1183                 return $e->event unless $e->allowed('VIEW_HOLD');
1184         }
1185
1186         return _hold_status($e, $hold);
1187
1188 }
1189
1190 sub _hold_status {
1191         my($e, $hold) = @_;
1192     if ($hold->cancel_time) {
1193         return 6;
1194     }
1195     if ($U->is_true($hold->frozen) && !$hold->capture_time) {
1196         return 7;
1197     }
1198     if ($hold->current_shelf_lib and $hold->current_shelf_lib ne $hold->pickup_lib) {
1199         return 8;
1200     }
1201         return 1 unless $hold->current_copy;
1202         return 2 unless $hold->capture_time;
1203
1204         my $copy = $hold->current_copy;
1205         unless( ref $copy ) {
1206                 $copy = $e->retrieve_asset_copy($hold->current_copy)
1207                         or return $e->event;
1208         }
1209
1210         return 3 if $copy->status == OILS_COPY_STATUS_IN_TRANSIT;
1211
1212         if($copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF) {
1213
1214         my $hs_wait_interval = $U->ou_ancestor_setting_value($hold->pickup_lib, 'circ.hold_shelf_status_delay');
1215         return 4 unless $hs_wait_interval;
1216
1217         # if a hold_shelf_status_delay interval is defined and start_time plus 
1218         # the interval is greater than now, consider the hold to be in the virtual 
1219         # "on its way to the holds shelf" status. Return 5.
1220
1221         my $transit    = $e->search_action_hold_transit_copy({hold => $hold->id})->[0];
1222         my $start_time = ($transit) ? $transit->dest_recv_time : $hold->capture_time;
1223         $start_time    = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($start_time));
1224         my $end_time   = $start_time->add(seconds => OpenSRF::Utils::interval_to_seconds($hs_wait_interval));
1225
1226         return 5 if $end_time > DateTime->now;
1227         return 4;
1228     }
1229
1230     return -1;  # error
1231 }
1232
1233
1234
1235 __PACKAGE__->register_method(
1236     method    => "retrieve_hold_queue_stats",
1237     api_name  => "open-ils.circ.hold.queue_stats.retrieve",
1238     signature => {
1239         desc   => 'Returns summary data about the state of a hold',
1240         params => [
1241             { desc => 'Authentication token',  type => 'string'},
1242             { desc => 'Hold ID', type => 'number'},
1243         ],
1244         return => {
1245             desc => q/Summary object with keys: 
1246                 total_holds : total holds in queue
1247                 queue_position : current queue position
1248                 potential_copies : number of potential copies for this hold
1249                 estimated_wait : estimated wait time in days
1250                 status : hold status  
1251                      -1 => error or unexpected state,
1252                      1 => 'waiting for copy to become available',
1253                      2 => 'waiting for copy capture',
1254                      3 => 'in transit',
1255                      4 => 'arrived',
1256                      5 => 'hold-shelf-delay'
1257             /,
1258             type => 'object'
1259         }
1260     }
1261 );
1262
1263 sub retrieve_hold_queue_stats {
1264     my($self, $conn, $auth, $hold_id) = @_;
1265         my $e = new_editor(authtoken => $auth);
1266         return $e->event unless $e->checkauth;
1267         my $hold = $e->retrieve_action_hold_request($hold_id) or return $e->event;
1268         if($e->requestor->id != $hold->usr) {
1269                 return $e->event unless $e->allowed('VIEW_HOLD');
1270         }
1271     return retrieve_hold_queue_status_impl($e, $hold);
1272 }
1273
1274 sub retrieve_hold_queue_status_impl {
1275     my $e = shift;
1276     my $hold = shift;
1277
1278     # The holds queue is defined as the distinct set of holds that share at 
1279     # least one potential copy with the context hold, plus any holds that
1280     # share the same hold type and target.  The latter part exists to
1281     # accomodate holds that currently have no potential copies
1282     my $q_holds = $e->json_query({
1283
1284         # fetch cut_in_line and request_time since they're in the order_by
1285         # and we're asking for distinct values
1286         select => {ahr => ['id', 'cut_in_line', 'request_time']},
1287         from   => {
1288             ahr => {
1289                 'ahcm' => {
1290                     join => {
1291                         'ahcm2' => {
1292                             'class' => 'ahcm',
1293                             'field' => 'target_copy',
1294                             'fkey'  => 'target_copy'
1295                         }
1296                     }
1297                 }
1298             }
1299         },
1300         order_by => [
1301             {
1302                 "class" => "ahr",
1303                 "field" => "cut_in_line",
1304                 "transform" => "coalesce",
1305                 "params" => [ 0 ],
1306                 "direction" => "desc"
1307             },
1308             { "class" => "ahr", "field" => "request_time" }
1309         ],
1310         distinct => 1,
1311         where => {
1312             '+ahcm2' => { hold => $hold->id }
1313         }
1314     });
1315
1316     if (!@$q_holds) { # none? maybe we don't have a map ... 
1317         $q_holds = $e->json_query({
1318             select => {ahr => ['id', 'cut_in_line', 'request_time']},
1319             from   => 'ahr',
1320             order_by => [
1321                 {
1322                     "class" => "ahr",
1323                     "field" => "cut_in_line",
1324                     "transform" => "coalesce",
1325                     "params" => [ 0 ],
1326                     "direction" => "desc"
1327                 },
1328                 { "class" => "ahr", "field" => "request_time" }
1329             ],
1330             where    => {
1331                 hold_type => $hold->hold_type, 
1332                 target    => $hold->target 
1333            } 
1334         });
1335     }
1336
1337
1338     my $qpos = 1;
1339     for my $h (@$q_holds) {
1340         last if $h->{id} == $hold->id;
1341         $qpos++;
1342     }
1343
1344     my $hold_data = $e->json_query({
1345         select => {
1346             acp => [ {column => 'id', transform => 'count', aggregate => 1, alias => 'count'} ],
1347             ccm => [ {column =>'avg_wait_time'} ]
1348         }, 
1349         from => {
1350             ahcm => {
1351                 acp => {
1352                     join => {
1353                         ccm => {type => 'left'}
1354                     }
1355                 }
1356             }
1357         }, 
1358         where => {'+ahcm' => {hold => $hold->id} }
1359     });
1360
1361     my $user_org = $e->json_query({select => {au => ['home_ou']}, from => 'au', where => {id => $hold->usr}})->[0]->{home_ou};
1362
1363     my $default_wait = $U->ou_ancestor_setting_value($user_org, OILS_SETTING_HOLD_ESIMATE_WAIT_INTERVAL);
1364     my $min_wait = $U->ou_ancestor_setting_value($user_org, 'circ.holds.min_estimated_wait_interval');
1365     $min_wait = OpenSRF::Utils::interval_to_seconds($min_wait || '0 seconds');
1366     $default_wait ||= '0 seconds';
1367
1368     # Estimated wait time is the average wait time across the set 
1369     # of potential copies, divided by the number of potential copies
1370     # times the queue position.  
1371
1372     my $combined_secs = 0;
1373     my $num_potentials = 0;
1374
1375     for my $wait_data (@$hold_data) {
1376         my $count += $wait_data->{count};
1377         $combined_secs += $count * 
1378             OpenSRF::Utils::interval_to_seconds($wait_data->{avg_wait_time} || $default_wait);
1379         $num_potentials += $count;
1380     }
1381
1382     my $estimated_wait = -1;
1383
1384     if($num_potentials) {
1385         my $avg_wait = $combined_secs / $num_potentials;
1386         $estimated_wait = $qpos * ($avg_wait / $num_potentials);
1387         $estimated_wait = $min_wait if $estimated_wait < $min_wait and $estimated_wait != -1;
1388     }
1389
1390     return {
1391         total_holds      => scalar(@$q_holds),
1392         queue_position   => $qpos,
1393         potential_copies => $num_potentials,
1394         status           => _hold_status( $e, $hold ),
1395         estimated_wait   => int($estimated_wait)
1396     };
1397 }
1398
1399
1400 sub fetch_open_hold_by_current_copy {
1401         my $class = shift;
1402         my $copyid = shift;
1403         my $hold = $apputils->simplereq(
1404                 'open-ils.cstore', 
1405                 'open-ils.cstore.direct.action.hold_request.search.atomic',
1406                 { current_copy =>  $copyid , cancel_time => undef, fulfillment_time => undef });
1407         return $hold->[0] if ref($hold);
1408         return undef;
1409 }
1410
1411 sub fetch_related_holds {
1412         my $class = shift;
1413         my $copyid = shift;
1414         return $apputils->simplereq(
1415                 'open-ils.cstore', 
1416                 'open-ils.cstore.direct.action.hold_request.search.atomic',
1417                 { current_copy =>  $copyid , cancel_time => undef, fulfillment_time => undef });
1418 }
1419
1420
1421 __PACKAGE__->register_method(
1422     method    => "hold_pull_list",
1423     api_name  => "open-ils.circ.hold_pull_list.retrieve",
1424     signature => {
1425         desc   => 'Returns (reference to) a list of holds that need to be "pulled" by a given location. ' .
1426                   'The location is determined by the login session.',
1427         params => [
1428             { desc => 'Limit (optional)',  type => 'number'},
1429             { desc => 'Offset (optional)', type => 'number'},
1430         ],
1431         return => {
1432             desc => 'reference to a list of holds, or event on failure',
1433         }
1434     }
1435 );
1436
1437 __PACKAGE__->register_method(
1438     method    => "hold_pull_list",
1439     api_name  => "open-ils.circ.hold_pull_list.id_list.retrieve",
1440     signature => {
1441         desc   => 'Returns (reference to) a list of holds IDs that need to be "pulled" by a given location. ' .
1442                   'The location is determined by the login session.',
1443         params => [
1444             { desc => 'Limit (optional)',  type => 'number'},
1445             { desc => 'Offset (optional)', type => 'number'},
1446         ],
1447         return => {
1448             desc => 'reference to a list of holds, or event on failure',
1449         }
1450     }
1451 );
1452
1453 __PACKAGE__->register_method(
1454     method    => "hold_pull_list",
1455     api_name  => "open-ils.circ.hold_pull_list.retrieve.count",
1456     signature => {
1457         desc   => 'Returns a count of holds that need to be "pulled" by a given location. ' .
1458                   'The location is determined by the login session.',
1459         params => [
1460             { desc => 'Limit (optional)',  type => 'number'},
1461             { desc => 'Offset (optional)', type => 'number'},
1462         ],
1463         return => {
1464             desc => 'Holds count (integer), or event on failure',
1465             # type => 'number'
1466         }
1467     }
1468 );
1469
1470
1471 sub hold_pull_list {
1472         my( $self, $conn, $authtoken, $limit, $offset ) = @_;
1473         my( $reqr, $evt ) = $U->checkses($authtoken);
1474         return $evt if $evt;
1475
1476         my $org = $reqr->ws_ou || $reqr->home_ou;
1477         # the perm locaiton shouldn't really matter here since holds
1478         # will exist all over and VIEW_HOLDS should be universal
1479         $evt = $U->check_perms($reqr->id, $org, 'VIEW_HOLD');
1480         return $evt if $evt;
1481
1482     if($self->api_name =~ /count/) {
1483
1484                 my $count = $U->storagereq(
1485                         'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
1486                         $org, $limit, $offset ); 
1487
1488         $logger->info("Grabbing pull list for org unit $org with $count items");
1489         return $count;
1490
1491     } elsif( $self->api_name =~ /id_list/ ) {
1492                 return $U->storagereq(
1493                         'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1494                         $org, $limit, $offset ); 
1495
1496         } else {
1497                 return $U->storagereq(
1498                         'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered.atomic',
1499                         $org, $limit, $offset ); 
1500         }
1501 }
1502
1503 __PACKAGE__->register_method(
1504     method    => "print_hold_pull_list",
1505     api_name  => "open-ils.circ.hold_pull_list.print",
1506     signature => {
1507         desc   => 'Returns an HTML-formatted holds pull list',
1508         params => [
1509             { desc => 'Authtoken', type => 'string'},
1510             { desc => 'Org unit ID.  Optional, defaults to workstation org unit', type => 'number'},
1511         ],
1512         return => {
1513             desc => 'HTML string',
1514             type => 'string'
1515         }
1516     }
1517 );
1518
1519 sub print_hold_pull_list {
1520     my($self, $client, $auth, $org_id) = @_;
1521
1522     my $e = new_editor(authtoken=>$auth);
1523     return $e->event unless $e->checkauth;
1524
1525     $org_id = (defined $org_id) ? $org_id : $e->requestor->ws_ou;
1526     return $e->event unless $e->allowed('VIEW_HOLD', $org_id);
1527
1528     my $hold_ids = $U->storagereq(
1529         'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered.atomic',
1530         $org_id, 10000);
1531
1532     return undef unless @$hold_ids;
1533
1534     $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1535
1536     # Holds will /NOT/ be in order after this ...
1537     my $holds = $e->search_action_hold_request({id => $hold_ids}, {substream => 1});
1538     $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1539
1540     # ... so we must resort.
1541     my $hold_map = +{map { $_->id => $_ } @$holds};
1542     my $sorted_holds = [];
1543     push @$sorted_holds, $hold_map->{$_} foreach @$hold_ids;
1544
1545     return $U->fire_object_event(
1546         undef, "ahr.format.pull_list", $sorted_holds,
1547         $org_id, undef, undef, $client
1548     );
1549
1550 }
1551
1552 __PACKAGE__->register_method(
1553     method    => "print_hold_pull_list_stream",
1554     stream   => 1,
1555     api_name  => "open-ils.circ.hold_pull_list.print.stream",
1556     signature => {
1557         desc   => 'Returns a stream of fleshed holds',
1558         params => [
1559             { desc => 'Authtoken', type => 'string'},
1560             { 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)',
1561               type => 'object'
1562             },
1563         ],
1564         return => {
1565             desc => 'A stream of fleshed holds',
1566             type => 'object'
1567         }
1568     }
1569 );
1570
1571 sub print_hold_pull_list_stream {
1572     my($self, $client, $auth, $params) = @_;
1573
1574     my $e = new_editor(authtoken=>$auth);
1575     return $e->die_event unless $e->checkauth;
1576
1577     delete($$params{org_id}) unless (int($$params{org_id}));
1578     delete($$params{limit}) unless (int($$params{limit}));
1579     delete($$params{offset}) unless (int($$params{offset}));
1580     delete($$params{chunk_size}) unless (int($$params{chunk_size}));
1581     delete($$params{chunk_size}) if  ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
1582     $$params{chunk_size} ||= 10;
1583
1584     $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
1585     return $e->die_event unless $e->allowed('VIEW_HOLD', $$params{org_id });
1586
1587     my $sort = [];
1588     if ($$params{sort} && @{ $$params{sort} }) {
1589         for my $s (@{ $$params{sort} }) {
1590             if ($s eq 'acplo.position') {
1591                 push @$sort, {
1592                     "class" => "acplo", "field" => "position",
1593                     "transform" => "coalesce", "params" => [999]
1594                 };
1595             } elsif ($s eq 'prefix') {
1596                 push @$sort, {"class" => "acnp", "field" => "label_sortkey"};
1597             } elsif ($s eq 'call_number') {
1598                 push @$sort, {"class" => "acn", "field" => "label_sortkey"};
1599             } elsif ($s eq 'suffix') {
1600                 push @$sort, {"class" => "acns", "field" => "label_sortkey"};
1601             } elsif ($s eq 'request_time') {
1602                 push @$sort, {"class" => "ahr", "field" => "request_time"};
1603             }
1604         }
1605     } else {
1606         push @$sort, {"class" => "ahr", "field" => "request_time"};
1607     }
1608
1609     my $holds_ids = $e->json_query(
1610         {
1611             "select" => {"ahr" => ["id"]},
1612             "from" => {
1613                 "ahr" => {
1614                     "acp" => { 
1615                         "field" => "id",
1616                         "fkey" => "current_copy",
1617                         "filter" => {
1618                             "circ_lib" => $$params{org_id}, "status" => [0,7]
1619                         },
1620                         "join" => {
1621                             "acn" => {
1622                                 "field" => "id",
1623                                 "fkey" => "call_number",
1624                                 "join" => {
1625                                     "acnp" => {
1626                                         "field" => "id",
1627                                         "fkey" => "prefix"
1628                                     },
1629                                     "acns" => {
1630                                         "field" => "id",
1631                                         "fkey" => "suffix"
1632                                     }
1633                                 }
1634                             },
1635                             "acplo" => {
1636                                 "field" => "org",
1637                                 "fkey" => "circ_lib", 
1638                                 "type" => "left",
1639                                 "filter" => {
1640                                     "location" => {"=" => {"+acp" => "location"}}
1641                                 }
1642                             }
1643                         }
1644                     }
1645                 }
1646             },
1647             "where" => {
1648                 "+ahr" => {
1649                     "capture_time" => undef,
1650                     "cancel_time" => undef,
1651                     "-or" => [
1652                         {"expire_time" => undef },
1653                         {"expire_time" => {">" => "now"}}
1654                     ]
1655                 }
1656             },
1657             (@$sort ? (order_by => $sort) : ()),
1658             ($$params{limit} ? (limit => $$params{limit}) : ()),
1659             ($$params{offset} ? (offset => $$params{offset}) : ())
1660         }, {"substream" => 1}
1661     ) or return $e->die_event;
1662
1663     $logger->info("about to stream back " . scalar(@$holds_ids) . " holds");
1664
1665     my @chunk;
1666     for my $hid (@$holds_ids) {
1667         push @chunk, $e->retrieve_action_hold_request([
1668             $hid->{"id"}, {
1669                 "flesh" => 3,
1670                 "flesh_fields" => {
1671                     "ahr" => ["usr", "current_copy"],
1672                     "au"  => ["card"],
1673                     "acp" => ["location", "call_number", "parts"],
1674                     "acn" => ["record","prefix","suffix"]
1675                 }
1676             }
1677         ]);
1678
1679         if (@chunk >= $$params{chunk_size}) {
1680             $client->respond( \@chunk );
1681             @chunk = ();
1682         }
1683     }
1684     $client->respond_complete( \@chunk ) if (@chunk);
1685     $e->disconnect;
1686     return undef;
1687 }
1688
1689
1690
1691 __PACKAGE__->register_method(
1692     method        => 'fetch_hold_notify',
1693     api_name      => 'open-ils.circ.hold_notification.retrieve_by_hold',
1694     authoritative => 1,
1695     signature     => q/ 
1696 Returns a list of hold notification objects based on hold id.
1697 @param authtoken The loggin session key
1698 @param holdid The id of the hold whose notifications we want to retrieve
1699 @return An array of hold notification objects, event on error.
1700 /
1701 );
1702
1703 sub fetch_hold_notify {
1704         my( $self, $conn, $authtoken, $holdid ) = @_;
1705         my( $requestor, $evt ) = $U->checkses($authtoken);
1706         return $evt if $evt;
1707         my ($hold, $patron);
1708         ($hold, $evt) = $U->fetch_hold($holdid);
1709         return $evt if $evt;
1710         ($patron, $evt) = $U->fetch_user($hold->usr);
1711         return $evt if $evt;
1712
1713         $evt = $U->check_perms($requestor->id, $patron->home_ou, 'VIEW_HOLD_NOTIFICATION');
1714         return $evt if $evt;
1715
1716         $logger->info("User ".$requestor->id." fetching hold notifications for hold $holdid");
1717         return $U->cstorereq(
1718                 'open-ils.cstore.direct.action.hold_notification.search.atomic', {hold => $holdid} );
1719 }
1720
1721
1722 __PACKAGE__->register_method(
1723     method    => 'create_hold_notify',
1724     api_name  => 'open-ils.circ.hold_notification.create',
1725     signature => q/
1726 Creates a new hold notification object
1727 @param authtoken The login session key
1728 @param notification The hold notification object to create
1729 @return ID of the new object on success, Event on error
1730 /
1731 );
1732
1733 sub create_hold_notify {
1734    my( $self, $conn, $auth, $note ) = @_;
1735    my $e = new_editor(authtoken=>$auth, xact=>1);
1736    return $e->die_event unless $e->checkauth;
1737
1738    my $hold = $e->retrieve_action_hold_request($note->hold)
1739       or return $e->die_event;
1740    my $patron = $e->retrieve_actor_user($hold->usr) 
1741       or return $e->die_event;
1742
1743    return $e->die_event unless 
1744       $e->allowed('CREATE_HOLD_NOTIFICATION', $patron->home_ou);
1745
1746    $note->notify_staff($e->requestor->id);
1747    $e->create_action_hold_notification($note) or return $e->die_event;
1748    $e->commit;
1749    return $note->id;
1750 }
1751
1752 __PACKAGE__->register_method(
1753     method    => 'create_hold_note',
1754     api_name  => 'open-ils.circ.hold_note.create',
1755     signature => q/
1756                 Creates a new hold request note object
1757                 @param authtoken The login session key
1758                 @param note The hold note object to create
1759                 @return ID of the new object on success, Event on error
1760                 /
1761 );
1762
1763 sub create_hold_note {
1764    my( $self, $conn, $auth, $note ) = @_;
1765    my $e = new_editor(authtoken=>$auth, xact=>1);
1766    return $e->die_event unless $e->checkauth;
1767
1768    my $hold = $e->retrieve_action_hold_request($note->hold)
1769       or return $e->die_event;
1770    my $patron = $e->retrieve_actor_user($hold->usr) 
1771       or return $e->die_event;
1772
1773    return $e->die_event unless 
1774       $e->allowed('UPDATE_HOLD', $patron->home_ou); # FIXME: Using permcrud perm listed in fm_IDL.xml for ahrn.  Probably want something more specific
1775
1776    $e->create_action_hold_request_note($note) or return $e->die_event;
1777    $e->commit;
1778    return $note->id;
1779 }
1780
1781 __PACKAGE__->register_method(
1782     method    => 'reset_hold',
1783     api_name  => 'open-ils.circ.hold.reset',
1784     signature => q/
1785                 Un-captures and un-targets a hold, essentially returning
1786                 it to the state it was in directly after it was placed,
1787                 then attempts to re-target the hold
1788                 @param authtoken The login session key
1789                 @param holdid The id of the hold
1790         /
1791 );
1792
1793
1794 sub reset_hold {
1795         my( $self, $conn, $auth, $holdid ) = @_;
1796         my $reqr;
1797         my ($hold, $evt) = $U->fetch_hold($holdid);
1798         return $evt if $evt;
1799         ($reqr, $evt) = $U->checksesperm($auth, 'UPDATE_HOLD');
1800         return $evt if $evt;
1801         $evt = _reset_hold($self, $reqr, $hold);
1802         return $evt if $evt;
1803         return 1;
1804 }
1805
1806
1807 __PACKAGE__->register_method(
1808     method   => 'reset_hold_batch',
1809     api_name => 'open-ils.circ.hold.reset.batch'
1810 );
1811
1812 sub reset_hold_batch {
1813     my($self, $conn, $auth, $hold_ids) = @_;
1814
1815     my $e = new_editor(authtoken => $auth);
1816     return $e->event unless $e->checkauth;
1817
1818     for my $hold_id ($hold_ids) {
1819
1820         my $hold = $e->retrieve_action_hold_request(
1821             [$hold_id, {flesh => 1, flesh_fields => {ahr => ['usr']}}]) 
1822             or return $e->event;
1823
1824             next unless $e->allowed('UPDATE_HOLD', $hold->usr->home_ou);
1825         _reset_hold($self, $e->requestor, $hold);
1826     }
1827
1828     return 1;
1829 }
1830
1831
1832 sub _reset_hold {
1833         my ($self, $reqr, $hold) = @_;
1834
1835         my $e = new_editor(xact =>1, requestor => $reqr);
1836
1837         $logger->info("reseting hold ".$hold->id);
1838
1839         my $hid = $hold->id;
1840
1841         if( $hold->capture_time and $hold->current_copy ) {
1842
1843                 my $copy = $e->retrieve_asset_copy($hold->current_copy)
1844                         or return $e->die_event;
1845
1846                 if( $copy->status == OILS_COPY_STATUS_ON_HOLDS_SHELF ) {
1847                         $logger->info("setting copy to status 'reshelving' on hold retarget");
1848                         $copy->status(OILS_COPY_STATUS_RESHELVING);
1849                         $copy->editor($e->requestor->id);
1850                         $copy->edit_date('now');
1851                         $e->update_asset_copy($copy) or return $e->die_event;
1852
1853                 } elsif( $copy->status == OILS_COPY_STATUS_IN_TRANSIT ) {
1854
1855                         # We don't want the copy to remain "in transit"
1856                         $copy->status(OILS_COPY_STATUS_RESHELVING);
1857                         $logger->warn("! reseting hold [$hid] that is in transit");
1858                         my $transid = $e->search_action_hold_transit_copy({hold=>$hold->id},{idlist=>1})->[0];
1859
1860                         if( $transid ) {
1861                                 my $trans = $e->retrieve_action_transit_copy($transid);
1862                                 if( $trans ) {
1863                                         $logger->info("Aborting transit [$transid] on hold [$hid] reset...");
1864                                         my $evt = OpenILS::Application::Circ::Transit::__abort_transit($e, $trans, $copy, 1);
1865                                         $logger->info("Transit abort completed with result $evt");
1866                                         unless ("$evt" eq 1) {
1867                         $e->rollback;
1868                                             return $evt;
1869                     }
1870                                 }
1871                         }
1872                 }
1873         }
1874
1875         $hold->clear_capture_time;
1876         $hold->clear_current_copy;
1877         $hold->clear_shelf_time;
1878         $hold->clear_shelf_expire_time;
1879         $hold->clear_current_shelf_lib;
1880
1881         $e->update_action_hold_request($hold) or return $e->die_event;
1882         $e->commit;
1883
1884         $U->storagereq(
1885                 'open-ils.storage.action.hold_request.copy_targeter', undef, $hold->id );
1886
1887         return undef;
1888 }
1889
1890
1891 __PACKAGE__->register_method(
1892     method    => 'fetch_open_title_holds',
1893     api_name  => 'open-ils.circ.open_holds.retrieve',
1894     signature => q/
1895                 Returns a list ids of un-fulfilled holds for a given title id
1896                 @param authtoken The login session key
1897                 @param id the id of the item whose holds we want to retrieve
1898                 @param type The hold type - M, T, I, V, C, F, R
1899         /
1900 );
1901
1902 sub fetch_open_title_holds {
1903         my( $self, $conn, $auth, $id, $type, $org ) = @_;
1904         my $e = new_editor( authtoken => $auth );
1905         return $e->event unless $e->checkauth;
1906
1907         $type ||= "T";
1908         $org  ||= $e->requestor->ws_ou;
1909
1910 #       return $e->search_action_hold_request(
1911 #               { target => $id, hold_type => $type, fulfillment_time => undef }, {idlist=>1});
1912
1913         # XXX make me return IDs in the future ^--
1914         my $holds = $e->search_action_hold_request(
1915                 { 
1916                         target                          => $id, 
1917                         cancel_time                     => undef, 
1918                         hold_type                       => $type, 
1919                         fulfillment_time        => undef 
1920                 }
1921         );
1922
1923         flesh_hold_transits($holds);
1924         return $holds;
1925 }
1926
1927
1928 sub flesh_hold_transits {
1929         my $holds = shift;
1930         for my $hold ( @$holds ) {
1931                 $hold->transit(
1932                         $apputils->simplereq(
1933                                 'open-ils.cstore',
1934                                 "open-ils.cstore.direct.action.hold_transit_copy.search.atomic",
1935                                 { hold => $hold->id },
1936                                 { order_by => { ahtc => 'id desc' }, limit => 1 }
1937                         )->[0]
1938                 );
1939         }
1940 }
1941
1942 sub flesh_hold_notices {
1943         my( $holds, $e ) = @_;
1944         $e ||= new_editor();
1945
1946         for my $hold (@$holds) {
1947                 my $notices = $e->search_action_hold_notification(
1948                         [
1949                                 { hold => $hold->id },
1950                                 { order_by => { anh => 'notify_time desc' } },
1951                         ],
1952                         {idlist=>1}
1953                 );
1954
1955                 $hold->notify_count(scalar(@$notices));
1956                 if( @$notices ) {
1957                         my $n = $e->retrieve_action_hold_notification($$notices[0])
1958                                 or return $e->event;
1959                         $hold->notify_time($n->notify_time);
1960                 }
1961         }
1962 }
1963
1964
1965 __PACKAGE__->register_method(
1966     method    => 'fetch_captured_holds',
1967     api_name  => 'open-ils.circ.captured_holds.on_shelf.retrieve',
1968     stream    => 1,
1969     authoritative => 1,
1970     signature => q/
1971                 Returns a list of un-fulfilled holds (on the Holds Shelf) for a given title id
1972                 @param authtoken The login session key
1973                 @param org The org id of the location in question
1974                 @param match_copy A specific copy to limit to
1975         /
1976 );
1977
1978 __PACKAGE__->register_method(
1979     method    => 'fetch_captured_holds',
1980     api_name  => 'open-ils.circ.captured_holds.id_list.on_shelf.retrieve',
1981     stream    => 1,
1982     authoritative => 1,
1983     signature => q/
1984                 Returns list ids of un-fulfilled holds (on the Holds Shelf) for a given title id
1985                 @param authtoken The login session key
1986                 @param org The org id of the location in question
1987                 @param match_copy A specific copy to limit to
1988         /
1989 );
1990
1991 __PACKAGE__->register_method(
1992     method    => 'fetch_captured_holds',
1993     api_name  => 'open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve',
1994     stream    => 1,
1995     authoritative => 1,
1996     signature => q/
1997                 Returns list ids of shelf-expired un-fulfilled holds for a given title id
1998                 @param authtoken The login session key
1999                 @param org The org id of the location in question
2000                 @param match_copy A specific copy to limit to
2001         /
2002 );
2003
2004
2005 sub fetch_captured_holds {
2006         my( $self, $conn, $auth, $org, $match_copy ) = @_;
2007
2008         my $e = new_editor(authtoken => $auth);
2009         return $e->die_event unless $e->checkauth;
2010         return $e->die_event unless $e->allowed('VIEW_HOLD'); # XXX rely on editor perm
2011
2012         $org ||= $e->requestor->ws_ou;
2013
2014         my $current_copy = { '!=' => undef };
2015         $current_copy = { '=' => $match_copy } if $match_copy;
2016
2017     my $query = { 
2018         select => { alhr => ['id'] },
2019         from   => {
2020             alhr => {
2021                 acp => {
2022                     field => 'id',
2023                     fkey  => 'current_copy'
2024                 },
2025             }
2026         }, 
2027         where => {
2028             '+acp' => { status => OILS_COPY_STATUS_ON_HOLDS_SHELF },
2029             '+alhr' => {
2030                 capture_time     => { "!=" => undef },
2031                 current_copy     => $current_copy,
2032                 fulfillment_time => undef,
2033                 current_shelf_lib => $org
2034             }
2035         }
2036     };
2037     if($self->api_name =~ /expired/) {
2038         $query->{'where'}->{'+alhr'}->{'-or'} = {
2039                 shelf_expire_time => { '<' => 'now'},
2040                 cancel_time => { '!=' => undef },
2041         };
2042     }
2043     my $hold_ids = $e->json_query( $query );
2044
2045     for my $hold_id (@$hold_ids) {
2046         if($self->api_name =~ /id_list/) {
2047             $conn->respond($hold_id->{id});
2048             next;
2049         } else {
2050             $conn->respond(
2051                 $e->retrieve_action_hold_request([
2052                     $hold_id->{id},
2053                     {
2054                         flesh => 1,
2055                         flesh_fields => {ahr => ['notifications', 'transit', 'notes']},
2056                         order_by => {anh => 'notify_time desc'}
2057                     }
2058                 ])
2059             );
2060         }
2061     }
2062
2063     return undef;
2064 }
2065
2066 __PACKAGE__->register_method(
2067     method    => "print_expired_holds_stream",
2068     api_name  => "open-ils.circ.captured_holds.expired.print.stream",
2069     stream    => 1
2070 );
2071
2072 sub print_expired_holds_stream {
2073     my ($self, $client, $auth, $params) = @_;
2074
2075     # No need to check specific permissions: we're going to call another method
2076     # that will do that.
2077     my $e = new_editor("authtoken" => $auth);
2078     return $e->die_event unless $e->checkauth;
2079
2080     delete($$params{org_id}) unless (int($$params{org_id}));
2081     delete($$params{limit}) unless (int($$params{limit}));
2082     delete($$params{offset}) unless (int($$params{offset}));
2083     delete($$params{chunk_size}) unless (int($$params{chunk_size}));
2084     delete($$params{chunk_size}) if  ($$params{chunk_size} && $$params{chunk_size} > 50); # keep the size reasonable
2085     $$params{chunk_size} ||= 10;
2086
2087     $$params{org_id} = (defined $$params{org_id}) ? $$params{org_id}: $e->requestor->ws_ou;
2088
2089     my @hold_ids = $self->method_lookup(
2090         "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
2091     )->run($auth, $params->{"org_id"});
2092
2093     if (!@hold_ids) {
2094         $e->disconnect;
2095         return;
2096     } elsif (defined $U->event_code($hold_ids[0])) {
2097         $e->disconnect;
2098         return $hold_ids[0];
2099     }
2100
2101     $logger->info("about to stream back up to " . scalar(@hold_ids) . " expired holds");
2102
2103     while (@hold_ids) {
2104         my @hid_chunk = splice @hold_ids, 0, $params->{"chunk_size"};
2105
2106         my $result_chunk = $e->json_query({
2107             "select" => {
2108                 "acp" => ["barcode"],
2109                 "au" => [qw/
2110                     first_given_name second_given_name family_name alias
2111                 /],
2112                 "acn" => ["label"],
2113                 "bre" => ["marc"],
2114                 "acpl" => ["name"]
2115             },
2116             "from" => {
2117                 "ahr" => {
2118                     "acp" => {
2119                         "field" => "id", "fkey" => "current_copy",
2120                         "join" => {
2121                             "acn" => {
2122                                 "field" => "id", "fkey" => "call_number",
2123                                 "join" => {
2124                                     "bre" => {
2125                                         "field" => "id", "fkey" => "record"
2126                                     }
2127                                 }
2128                             },
2129                             "acpl" => {"field" => "id", "fkey" => "location"}
2130                         }
2131                     },
2132                     "au" => {"field" => "id", "fkey" => "usr"}
2133                 }
2134             },
2135             "where" => {"+ahr" => {"id" => \@hid_chunk}}
2136         }) or return $e->die_event;
2137         $client->respond($result_chunk);
2138     }
2139
2140     $e->disconnect;
2141     undef;
2142 }
2143
2144 __PACKAGE__->register_method(
2145     method    => "check_title_hold_batch",
2146     api_name  => "open-ils.circ.title_hold.is_possible.batch",
2147     stream    => 1,
2148     signature => {
2149         desc  => '@see open-ils.circ.title_hold.is_possible.batch',
2150         params => [
2151             { desc => 'Authentication token',     type => 'string'},
2152             { desc => 'Array of Hash of named parameters', type => 'array'},
2153         ],
2154         return => {
2155             desc => 'Array of response objects',
2156             type => 'array'
2157         }
2158     }
2159 );
2160
2161 sub check_title_hold_batch {
2162     my($self, $client, $authtoken, $param_list) = @_;
2163     foreach (@$param_list) {
2164         my ($res) = $self->method_lookup('open-ils.circ.title_hold.is_possible')->run($authtoken, $_);
2165         $client->respond($res);
2166     }
2167     return undef;
2168 }
2169
2170
2171 __PACKAGE__->register_method(
2172     method    => "check_title_hold",
2173     api_name  => "open-ils.circ.title_hold.is_possible",
2174     signature => {
2175         desc  => 'Determines if a hold were to be placed by a given user, ' .
2176              'whether or not said hold would have any potential copies to fulfill it.' .
2177              'The named paramaters of the second argument include: ' .
2178              'patronid, titleid, volume_id, copy_id, mrid, depth, pickup_lib, hold_type, selection_ou. ' .
2179              'See perldoc ' . __PACKAGE__ . ' for more info on these fields.' , 
2180         params => [
2181             { desc => 'Authentication token',     type => 'string'},
2182             { desc => 'Hash of named parameters', type => 'object'},
2183         ],
2184         return => {
2185             desc => 'List of new message IDs (empty if none)',
2186             type => 'array'
2187         }
2188     }
2189 );
2190
2191 =head3 check_title_hold (token, hash)
2192
2193 The named fields in the hash are: 
2194
2195  patronid     - ID of the hold recipient  (required)
2196  depth        - hold range depth          (default 0)
2197  pickup_lib   - destination for hold, fallback value for selection_ou
2198  selection_ou - ID of org_unit establishing hard and soft hold boundary settings
2199  issuanceid   - ID of the issuance to be held, required for Issuance level hold
2200  partid       - ID of the monograph part to be held, required for monograph part level hold
2201  titleid      - ID (BRN) of the title to be held, required for Title level hold
2202  volume_id    - required for Volume level hold
2203  copy_id      - required for Copy level hold
2204  mrid         - required for Meta-record level hold
2205  hold_type    - T, C (or R or F), I, V or M for Title, Copy, Issuance, Volume or Meta-record  (default "T")
2206
2207 All key/value pairs are passed on to do_possibility_checks.
2208
2209 =cut
2210
2211 # FIXME: better params checking.  what other params are required, if any?
2212 # FIXME: 3 copies of values confusing: $x, $params->{x} and $params{x}
2213 # FIXME: for example, $depth gets a default value, but then $$params{depth} is still 
2214 # used in conditionals, where it may be undefined, causing a warning.
2215 # FIXME: specify proper usage/interaction of selection_ou and pickup_lib
2216
2217 sub check_title_hold {
2218     my( $self, $client, $authtoken, $params ) = @_;
2219     my $e = new_editor(authtoken=>$authtoken);
2220     return $e->event unless $e->checkauth;
2221
2222     my %params       = %$params;
2223     my $depth        = $params{depth}        || 0;
2224     my $selection_ou = $params{selection_ou} || $params{pickup_lib};
2225
2226         my $patron = $e->retrieve_actor_user($params{patronid})
2227                 or return $e->event;
2228
2229         if( $e->requestor->id ne $patron->id ) {
2230                 return $e->event unless 
2231                         $e->allowed('VIEW_HOLD_PERMIT', $patron->home_ou);
2232         }
2233
2234         return OpenILS::Event->new('PATRON_BARRED') if $U->is_true($patron->barred);
2235
2236         my $request_lib = $e->retrieve_actor_org_unit($e->requestor->ws_ou)
2237                 or return $e->event;
2238
2239     my $soft_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_SOFT_BOUNDARY);
2240     my $hard_boundary = $U->ou_ancestor_setting_value($selection_ou, OILS_SETTING_HOLD_HARD_BOUNDARY);
2241
2242     my @status = ();
2243     my $return_depth = $hard_boundary; # default depth to return on success
2244     if(defined $soft_boundary and $depth < $soft_boundary) {
2245         # work up the tree and as soon as we find a potential copy, use that depth
2246         # also, make sure we don't go past the hard boundary if it exists
2247
2248         # our min boundary is the greater of user-specified boundary or hard boundary
2249         my $min_depth = (defined $hard_boundary and $hard_boundary > $depth) ?  
2250             $hard_boundary : $depth;
2251
2252         my $depth = $soft_boundary;
2253         while($depth >= $min_depth) {
2254             $logger->info("performing hold possibility check with soft boundary $depth");
2255             @status = do_possibility_checks($e, $patron, $request_lib, $depth, %params);
2256             if ($status[0]) {
2257                 $return_depth = $depth;
2258                 last;
2259             }
2260             $depth--;
2261         }
2262     } elsif(defined $hard_boundary and $depth < $hard_boundary) {
2263         # there is no soft boundary, enforce the hard boundary if it exists
2264         $logger->info("performing hold possibility check with hard boundary $hard_boundary");
2265         @status = do_possibility_checks($e, $patron, $request_lib, $hard_boundary, %params);
2266     } else {
2267         # no boundaries defined, fall back to user specifed boundary or no boundary
2268         $logger->info("performing hold possibility check with no boundary");
2269         @status = do_possibility_checks($e, $patron, $request_lib, $params{depth}, %params);
2270     }
2271
2272     my $place_unfillable = 0;
2273     $place_unfillable = 1 if $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
2274
2275     if ($status[0]) {
2276         return {
2277             "success" => 1,
2278             "depth" => $return_depth,
2279             "local_avail" => $status[1]
2280         };
2281     } elsif ($status[2]) {
2282         my $n = scalar @{$status[2]};
2283         return {"success" => 0, "last_event" => $status[2]->[$n - 1], "age_protected_copy" => $status[3], "place_unfillable" => $place_unfillable};
2284     } else {
2285         return {"success" => 0, "age_protected_copy" => $status[3], "place_unfillable" => $place_unfillable};
2286     }
2287 }
2288
2289
2290
2291 sub do_possibility_checks {
2292     my($e, $patron, $request_lib, $depth, %params) = @_;
2293
2294     my $issuanceid   = $params{issuanceid}      || "";
2295     my $partid       = $params{partid}      || "";
2296     my $titleid      = $params{titleid}      || "";
2297     my $volid        = $params{volume_id};
2298     my $copyid       = $params{copy_id};
2299     my $mrid         = $params{mrid}         || "";
2300     my $pickup_lib   = $params{pickup_lib};
2301     my $hold_type    = $params{hold_type}    || 'T';
2302     my $selection_ou = $params{selection_ou} || $pickup_lib;
2303     my $holdable_formats = $params{holdable_formats};
2304
2305
2306         my $copy;
2307         my $volume;
2308         my $title;
2309
2310         if( $hold_type eq OILS_HOLD_TYPE_FORCE || $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_COPY ) {
2311
2312         return $e->event unless $copy   = $e->retrieve_asset_copy($copyid);
2313         return $e->event unless $volume = $e->retrieve_asset_call_number($copy->call_number);
2314         return $e->event unless $title  = $e->retrieve_biblio_record_entry($volume->record);
2315
2316         return (1, 1, []) if( $hold_type eq OILS_HOLD_TYPE_RECALL || $hold_type eq OILS_HOLD_TYPE_FORCE);
2317         return verify_copy_for_hold( 
2318             $patron, $e->requestor, $title, $copy, $pickup_lib, $request_lib
2319         );
2320
2321         } elsif( $hold_type eq OILS_HOLD_TYPE_VOLUME ) {
2322
2323                 return $e->event unless $volume = $e->retrieve_asset_call_number($volid);
2324                 return $e->event unless $title  = $e->retrieve_biblio_record_entry($volume->record);
2325
2326                 return _check_volume_hold_is_possible(
2327                         $volume, $title, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2328         );
2329
2330         } elsif( $hold_type eq OILS_HOLD_TYPE_TITLE ) {
2331
2332                 return _check_title_hold_is_possible(
2333                         $titleid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2334         );
2335
2336         } elsif( $hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
2337
2338                 return _check_issuance_hold_is_possible(
2339                         $issuanceid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2340         );
2341
2342         } elsif( $hold_type eq OILS_HOLD_TYPE_MONOPART ) {
2343
2344                 return _check_monopart_hold_is_possible(
2345                         $partid, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou
2346         );
2347
2348         } elsif( $hold_type eq OILS_HOLD_TYPE_METARECORD ) {
2349
2350                 my $maps = $e->search_metabib_metarecord_source_map({metarecord=>$mrid});
2351                 my @recs = map { $_->source } @$maps;
2352                 my @status = ();
2353                 for my $rec (@recs) {
2354                         @status = _check_title_hold_is_possible(
2355                                 $rec, $depth, $request_lib, $patron, $e->requestor, $pickup_lib, $selection_ou, $holdable_formats
2356                         );
2357                         last if $status[0];
2358                 }
2359                 return @status;
2360         }
2361 #   else { Unrecognized hold_type ! }   # FIXME: return error? or 0?
2362 }
2363
2364 my %prox_cache;
2365 sub create_ranged_org_filter {
2366     my($e, $selection_ou, $depth) = @_;
2367
2368     # find the orgs from which this hold may be fulfilled, 
2369     # based on the selection_ou and depth
2370
2371     my $top_org = $e->search_actor_org_unit([
2372         {parent_ou => undef}, 
2373         {flesh=>1, flesh_fields=>{aou=>['ou_type']}}])->[0];
2374     my %org_filter;
2375
2376     return () if $depth == $top_org->ou_type->depth;
2377
2378     my $org_list = $U->storagereq('open-ils.storage.actor.org_unit.descendants.atomic', $selection_ou, $depth);
2379     %org_filter = (circ_lib => []);
2380     push(@{$org_filter{circ_lib}}, $_->id) for @$org_list;
2381
2382     $logger->info("hold org filter at depth $depth and selection_ou ".
2383         "$selection_ou created list of @{$org_filter{circ_lib}}");
2384
2385     return %org_filter;
2386 }
2387
2388
2389 sub _check_title_hold_is_possible {
2390     my( $titleid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou, $holdable_formats ) = @_;
2391    
2392     my ($types, $formats, $lang);
2393     if (defined($holdable_formats)) {
2394         ($types, $formats, $lang) = split '-', $holdable_formats;
2395     }
2396
2397     my $e = new_editor();
2398     my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2399
2400     # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2401     my $copies = $e->json_query(
2402         { 
2403             select => { acp => ['id', 'circ_lib'] },
2404               from => {
2405                 acp => {
2406                     acn => {
2407                         field  => 'id',
2408                         fkey   => 'call_number',
2409                         'join' => {
2410                             bre => {
2411                                 field  => 'id',
2412                                 filter => { id => $titleid },
2413                                 fkey   => 'record'
2414                             },
2415                             mrd => {
2416                                 field  => 'record',
2417                                 fkey   => 'record',
2418                                 filter => {
2419                                     record => $titleid,
2420                                     ( $types   ? (item_type => [split '', $types])   : () ),
2421                                     ( $formats ? (item_form => [split '', $formats]) : () ),
2422                                     ( $lang    ? (item_lang => $lang)                : () )
2423                                 }
2424                             }
2425                         }
2426                     },
2427                     acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2428                     ccs  => { field => 'id', filter => { holdable => 't'}, fkey => 'status'   },
2429                     acpm => { field => 'target_copy', type => 'left' } # ignore part-linked copies
2430                 }
2431             }, 
2432             where => {
2433                 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter },
2434                 '+acpm' => { target_copy => undef } # ignore part-linked copies
2435             }
2436         }
2437     );
2438
2439     $logger->info("title possible found ".scalar(@$copies)." potential copies");
2440     return (
2441         0, 0, [
2442             new OpenILS::Event(
2443                 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2444                 "payload" => {"fail_part" => "no_ultimate_items"}
2445             )
2446         ]
2447     ) unless @$copies;
2448
2449     # -----------------------------------------------------------------------
2450     # sort the copies into buckets based on their circ_lib proximity to 
2451     # the patron's home_ou.  
2452     # -----------------------------------------------------------------------
2453
2454     my $home_org = $patron->home_ou;
2455     my $req_org = $request_lib->id;
2456
2457     $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2458
2459     $prox_cache{$home_org} = 
2460         $e->search_actor_org_unit_proximity({from_org => $home_org})
2461         unless $prox_cache{$home_org};
2462     my $home_prox = $prox_cache{$home_org};
2463
2464     my %buckets;
2465     my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2466     push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2467
2468     my @keys = sort { $a <=> $b } keys %buckets;
2469
2470
2471     if( $home_org ne $req_org ) {
2472       # -----------------------------------------------------------------------
2473       # shove the copies close to the request_lib into the primary buckets 
2474       # directly before the farthest away copies.  That way, they are not 
2475       # given priority, but they are checked before the farthest copies.
2476       # -----------------------------------------------------------------------
2477         $prox_cache{$req_org} = 
2478             $e->search_actor_org_unit_proximity({from_org => $req_org})
2479             unless $prox_cache{$req_org};
2480         my $req_prox = $prox_cache{$req_org};
2481
2482         my %buckets2;
2483         my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2484         push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2485
2486         my $highest_key = $keys[@keys - 1];  # the farthest prox in the exising buckets
2487         my $new_key = $highest_key - 0.5; # right before the farthest prox
2488         my @keys2   = sort { $a <=> $b } keys %buckets2;
2489         for my $key (@keys2) {
2490             last if $key >= $highest_key;
2491             push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2492         }
2493     }
2494
2495     @keys = sort { $a <=> $b } keys %buckets;
2496
2497     my $title;
2498     my %seen;
2499     my @status;
2500     my $age_protect_only = 0;
2501     OUTER: for my $key (@keys) {
2502       my @cps = @{$buckets{$key}};
2503
2504       $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2505
2506       for my $copyid (@cps) {
2507
2508          next if $seen{$copyid};
2509          $seen{$copyid} = 1; # there could be dupes given the merged buckets
2510          my $copy = $e->retrieve_asset_copy($copyid);
2511          $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2512
2513          unless($title) { # grab the title if we don't already have it
2514             my $vol = $e->retrieve_asset_call_number(
2515                [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2516             $title = $vol->record;
2517          }
2518    
2519          @status = verify_copy_for_hold(
2520             $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2521
2522          $age_protect_only ||= $status[3];
2523          last OUTER if $status[0];
2524       }
2525     }
2526
2527     $status[3] = $age_protect_only;
2528     return @status;
2529 }
2530
2531 sub _check_issuance_hold_is_possible {
2532     my( $issuanceid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2533    
2534     my $e = new_editor();
2535     my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2536
2537     # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2538     my $copies = $e->json_query(
2539         { 
2540             select => { acp => ['id', 'circ_lib'] },
2541               from => {
2542                 acp => {
2543                     sitem => {
2544                         field  => 'unit',
2545                         fkey   => 'id',
2546                         filter => { issuance => $issuanceid }
2547                     },
2548                     acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2549                     ccs  => { field => 'id', filter => { holdable => 't'}, fkey => 'status'   }
2550                 }
2551             }, 
2552             where => {
2553                 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2554             },
2555             distinct => 1
2556         }
2557     );
2558
2559     $logger->info("issuance possible found ".scalar(@$copies)." potential copies");
2560
2561     my $empty_ok;
2562     if (!@$copies) {
2563         $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2564         $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2565
2566         return (
2567             0, 0, [
2568                 new OpenILS::Event(
2569                     "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2570                     "payload" => {"fail_part" => "no_ultimate_items"}
2571                 )
2572             ]
2573         ) unless $empty_ok;
2574
2575         return (1, 0);
2576     }
2577
2578     # -----------------------------------------------------------------------
2579     # sort the copies into buckets based on their circ_lib proximity to 
2580     # the patron's home_ou.  
2581     # -----------------------------------------------------------------------
2582
2583     my $home_org = $patron->home_ou;
2584     my $req_org = $request_lib->id;
2585
2586     $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2587
2588     $prox_cache{$home_org} = 
2589         $e->search_actor_org_unit_proximity({from_org => $home_org})
2590         unless $prox_cache{$home_org};
2591     my $home_prox = $prox_cache{$home_org};
2592
2593     my %buckets;
2594     my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2595     push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2596
2597     my @keys = sort { $a <=> $b } keys %buckets;
2598
2599
2600     if( $home_org ne $req_org ) {
2601       # -----------------------------------------------------------------------
2602       # shove the copies close to the request_lib into the primary buckets 
2603       # directly before the farthest away copies.  That way, they are not 
2604       # given priority, but they are checked before the farthest copies.
2605       # -----------------------------------------------------------------------
2606         $prox_cache{$req_org} = 
2607             $e->search_actor_org_unit_proximity({from_org => $req_org})
2608             unless $prox_cache{$req_org};
2609         my $req_prox = $prox_cache{$req_org};
2610
2611         my %buckets2;
2612         my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2613         push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2614
2615         my $highest_key = $keys[@keys - 1];  # the farthest prox in the exising buckets
2616         my $new_key = $highest_key - 0.5; # right before the farthest prox
2617         my @keys2   = sort { $a <=> $b } keys %buckets2;
2618         for my $key (@keys2) {
2619             last if $key >= $highest_key;
2620             push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2621         }
2622     }
2623
2624     @keys = sort { $a <=> $b } keys %buckets;
2625
2626     my $title;
2627     my %seen;
2628     my @status;
2629     my $age_protect_only = 0;
2630     OUTER: for my $key (@keys) {
2631       my @cps = @{$buckets{$key}};
2632
2633       $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2634
2635       for my $copyid (@cps) {
2636
2637          next if $seen{$copyid};
2638          $seen{$copyid} = 1; # there could be dupes given the merged buckets
2639          my $copy = $e->retrieve_asset_copy($copyid);
2640          $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2641
2642          unless($title) { # grab the title if we don't already have it
2643             my $vol = $e->retrieve_asset_call_number(
2644                [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2645             $title = $vol->record;
2646          }
2647    
2648          @status = verify_copy_for_hold(
2649             $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2650
2651          $age_protect_only ||= $status[3];
2652          last OUTER if $status[0];
2653       }
2654     }
2655
2656     if (!$status[0]) {
2657         if (!defined($empty_ok)) {
2658             $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_issuance_ok');
2659             $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2660         }
2661
2662         return (1,0) if ($empty_ok);
2663     }
2664     $status[3] = $age_protect_only;
2665     return @status;
2666 }
2667
2668 sub _check_monopart_hold_is_possible {
2669     my( $partid, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2670    
2671     my $e = new_editor();
2672     my %org_filter = create_ranged_org_filter($e, $selection_ou, $depth);
2673
2674     # this monster will grab the id and circ_lib of all of the "holdable" copies for the given record
2675     my $copies = $e->json_query(
2676         { 
2677             select => { acp => ['id', 'circ_lib'] },
2678               from => {
2679                 acp => {
2680                     acpm => {
2681                         field  => 'target_copy',
2682                         fkey   => 'id',
2683                         filter => { part => $partid }
2684                     },
2685                     acpl => { field => 'id', filter => { holdable => 't'}, fkey => 'location' },
2686                     ccs  => { field => 'id', filter => { holdable => 't'}, fkey => 'status'   }
2687                 }
2688             }, 
2689             where => {
2690                 '+acp' => { circulate => 't', deleted => 'f', holdable => 't', %org_filter }
2691             },
2692             distinct => 1
2693         }
2694     );
2695
2696     $logger->info("monopart possible found ".scalar(@$copies)." potential copies");
2697
2698     my $empty_ok;
2699     if (!@$copies) {
2700         $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2701         $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2702
2703         return (
2704             0, 0, [
2705                 new OpenILS::Event(
2706                     "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2707                     "payload" => {"fail_part" => "no_ultimate_items"}
2708                 )
2709             ]
2710         ) unless $empty_ok;
2711
2712         return (1, 0);
2713     }
2714
2715     # -----------------------------------------------------------------------
2716     # sort the copies into buckets based on their circ_lib proximity to 
2717     # the patron's home_ou.  
2718     # -----------------------------------------------------------------------
2719
2720     my $home_org = $patron->home_ou;
2721     my $req_org = $request_lib->id;
2722
2723     $logger->info("prox cache $home_org " . $prox_cache{$home_org});
2724
2725     $prox_cache{$home_org} = 
2726         $e->search_actor_org_unit_proximity({from_org => $home_org})
2727         unless $prox_cache{$home_org};
2728     my $home_prox = $prox_cache{$home_org};
2729
2730     my %buckets;
2731     my %hash = map { ($_->to_org => $_->prox) } @$home_prox;
2732     push( @{$buckets{ $hash{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2733
2734     my @keys = sort { $a <=> $b } keys %buckets;
2735
2736
2737     if( $home_org ne $req_org ) {
2738       # -----------------------------------------------------------------------
2739       # shove the copies close to the request_lib into the primary buckets 
2740       # directly before the farthest away copies.  That way, they are not 
2741       # given priority, but they are checked before the farthest copies.
2742       # -----------------------------------------------------------------------
2743         $prox_cache{$req_org} = 
2744             $e->search_actor_org_unit_proximity({from_org => $req_org})
2745             unless $prox_cache{$req_org};
2746         my $req_prox = $prox_cache{$req_org};
2747
2748         my %buckets2;
2749         my %hash2 = map { ($_->to_org => $_->prox) } @$req_prox;
2750         push( @{$buckets2{ $hash2{$_->{circ_lib}} } }, $_->{id} ) for @$copies;
2751
2752         my $highest_key = $keys[@keys - 1];  # the farthest prox in the exising buckets
2753         my $new_key = $highest_key - 0.5; # right before the farthest prox
2754         my @keys2   = sort { $a <=> $b } keys %buckets2;
2755         for my $key (@keys2) {
2756             last if $key >= $highest_key;
2757             push( @{$buckets{$new_key}}, $_ ) for @{$buckets2{$key}};
2758         }
2759     }
2760
2761     @keys = sort { $a <=> $b } keys %buckets;
2762
2763     my $title;
2764     my %seen;
2765     my @status;
2766     my $age_protect_only = 0;
2767     OUTER: for my $key (@keys) {
2768       my @cps = @{$buckets{$key}};
2769
2770       $logger->info("looking at " . scalar(@{$buckets{$key}}). " copies in proximity bucket $key");
2771
2772       for my $copyid (@cps) {
2773
2774          next if $seen{$copyid};
2775          $seen{$copyid} = 1; # there could be dupes given the merged buckets
2776          my $copy = $e->retrieve_asset_copy($copyid);
2777          $logger->debug("looking at bucket_key=$key, copy $copyid : circ_lib = " . $copy->circ_lib);
2778
2779          unless($title) { # grab the title if we don't already have it
2780             my $vol = $e->retrieve_asset_call_number(
2781                [ $copy->call_number, { flesh => 1, flesh_fields => { bre => ['fixed_fields'], acn => ['record'] } } ] );
2782             $title = $vol->record;
2783          }
2784    
2785          @status = verify_copy_for_hold(
2786             $patron, $requestor, $title, $copy, $pickup_lib, $request_lib);
2787
2788          $age_protect_only ||= $status[3];
2789          last OUTER if $status[0];
2790       }
2791     }
2792
2793     if (!$status[0]) {
2794         if (!defined($empty_ok)) {
2795             $empty_ok = $e->retrieve_config_global_flag('circ.holds.empty_part_ok');
2796             $empty_ok = ($empty_ok and $U->is_true($empty_ok->enabled));
2797         }
2798
2799         return (1,0) if ($empty_ok);
2800     }
2801     $status[3] = $age_protect_only;
2802     return @status;
2803 }
2804
2805
2806 sub _check_volume_hold_is_possible {
2807         my( $vol, $title, $depth, $request_lib, $patron, $requestor, $pickup_lib, $selection_ou ) = @_;
2808     my %org_filter = create_ranged_org_filter(new_editor(), $selection_ou, $depth);
2809         my $copies = new_editor->search_asset_copy({call_number => $vol->id, %org_filter});
2810         $logger->info("checking possibility of volume hold for volume ".$vol->id);
2811
2812     my $filter_copies = [];
2813     for my $copy (@$copies) {
2814         # ignore part-mapped copies for regular volume level holds
2815         push(@$filter_copies, $copy) unless
2816             new_editor->search_asset_copy_part_map({target_copy => $copy->id})->[0];
2817     }
2818     $copies = $filter_copies;
2819
2820     return (
2821         0, 0, [
2822             new OpenILS::Event(
2823                 "HIGH_LEVEL_HOLD_HAS_NO_COPIES",
2824                 "payload" => {"fail_part" => "no_ultimate_items"}
2825             )
2826         ]
2827     ) unless @$copies;
2828
2829     my @status;
2830     my $age_protect_only = 0;
2831         for my $copy ( @$copies ) {
2832         @status = verify_copy_for_hold(
2833                         $patron, $requestor, $title, $copy, $pickup_lib, $request_lib );
2834         $age_protect_only ||= $status[3];
2835         last if $status[0];
2836         }
2837     $status[3] = $age_protect_only;
2838         return @status;
2839 }
2840
2841
2842
2843 sub verify_copy_for_hold {
2844         my( $patron, $requestor, $title, $copy, $pickup_lib, $request_lib ) = @_;
2845         $logger->info("checking possibility of copy in hold request for copy ".$copy->id);
2846     my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2847                 {       patron                          => $patron, 
2848                         requestor                       => $requestor, 
2849                         copy                            => $copy,
2850                         title                           => $title, 
2851                         title_descriptor        => $title->fixed_fields, # this is fleshed into the title object
2852                         pickup_lib                      => $pickup_lib,
2853                         request_lib                     => $request_lib,
2854             new_hold            => 1,
2855             show_event_list     => 1
2856                 } 
2857         );
2858     my $age_protect_only = 0;
2859     if (@$permitted == 1 && @$permitted[0]->{textcode} eq 'ITEM_AGE_PROTECTED') {
2860         $age_protect_only = 1;
2861     }
2862
2863     return (
2864         (not scalar @$permitted), # true if permitted is an empty arrayref
2865         (   # XXX This test is of very dubious value; someone should figure
2866             # out what if anything is checking this value
2867                 ($copy->circ_lib == $pickup_lib) and 
2868             ($copy->status == OILS_COPY_STATUS_AVAILABLE)
2869         ),
2870         $permitted,
2871         $age_protect_only
2872     );
2873 }
2874
2875
2876
2877 sub find_nearest_permitted_hold {
2878
2879     my $class  = shift;
2880     my $editor = shift;     # CStoreEditor object
2881     my $copy   = shift;     # copy to target
2882     my $user   = shift;     # staff
2883     my $check_only = shift; # do no updates, just see if the copy could fulfill a hold
2884       
2885     my $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND');
2886
2887     my $bc = $copy->barcode;
2888
2889         # find any existing holds that already target this copy
2890         my $old_holds = $editor->search_action_hold_request(
2891                 {       current_copy => $copy->id, 
2892                         cancel_time  => undef, 
2893                         capture_time => undef 
2894                 } 
2895         );
2896
2897     my $hold_stall_interval = $U->ou_ancestor_setting_value($user->ws_ou, OILS_SETTING_HOLD_SOFT_STALL);
2898
2899         $logger->info("circulator: searching for best hold at org ".$user->ws_ou.
2900         " and copy $bc with a hold stalling interval of ". ($hold_stall_interval || "(none)"));
2901
2902         my $fifo = $U->ou_ancestor_setting_value($user->ws_ou, 'circ.holds_fifo');
2903
2904         # search for what should be the best holds for this copy to fulfill
2905         my $best_holds = $U->storagereq(
2906         "open-ils.storage.action.hold_request.nearest_hold.atomic", 
2907                 $user->ws_ou, $copy->id, 100, $hold_stall_interval, $fifo );
2908
2909         # Add any pre-targeted holds to the list too? Unless they are already there, anyway.
2910         if ($old_holds) {
2911                 for my $holdid (@$old_holds) {
2912                         next unless $holdid;
2913                         push(@$best_holds, $holdid) unless ( grep { ''.$holdid eq ''.$_ } @$best_holds );
2914                 }
2915         }
2916
2917         unless(@$best_holds) {
2918                 $logger->info("circulator: no suitable holds found for copy $bc");
2919                 return (undef, $evt);
2920         }
2921
2922
2923         my $best_hold;
2924
2925         # for each potential hold, we have to run the permit script
2926         # to make sure the hold is actually permitted.
2927     my %reqr_cache;
2928     my %org_cache;
2929         for my $holdid (@$best_holds) {
2930                 next unless $holdid;
2931                 $logger->info("circulator: checking if hold $holdid is permitted for copy $bc");
2932
2933                 my $hold = $editor->retrieve_action_hold_request($holdid) or next;
2934                 my $reqr = $reqr_cache{$hold->requestor} || $editor->retrieve_actor_user($hold->requestor);
2935                 my $rlib = $org_cache{$hold->request_lib} || $editor->retrieve_actor_org_unit($hold->request_lib);
2936
2937                 $reqr_cache{$hold->requestor} = $reqr;
2938                 $org_cache{$hold->request_lib} = $rlib;
2939
2940                 # see if this hold is permitted
2941                 my $permitted = OpenILS::Utils::PermitHold::permit_copy_hold(
2942                         {       patron_id                       => $hold->usr,
2943                                 requestor                       => $reqr,
2944                                 copy                            => $copy,
2945                                 pickup_lib                      => $hold->pickup_lib,
2946                                 request_lib                     => $rlib,
2947                                 retarget                        => 1
2948                         } 
2949                 );
2950
2951                 if( $permitted ) {
2952                         $best_hold = $hold;
2953                         last;
2954                 }
2955         }
2956
2957
2958         unless( $best_hold ) { # no "good" permitted holds were found
2959                 # we got nuthin
2960                 $logger->info("circulator: no suitable holds found for copy $bc");
2961                 return (undef, $evt);
2962         }
2963
2964         $logger->info("circulator: best hold ".$best_hold->id." found for copy $bc");
2965
2966         # indicate a permitted hold was found
2967         return $best_hold if $check_only;
2968
2969         # we've found a permitted hold.  we need to "grab" the copy 
2970         # to prevent re-targeted holds (next part) from re-grabbing the copy
2971         $best_hold->current_copy($copy->id);
2972         $editor->update_action_hold_request($best_hold) 
2973                 or return (undef, $editor->event);
2974
2975
2976     my @retarget;
2977
2978         # re-target any other holds that already target this copy
2979         for my $old_hold (@$old_holds) {
2980                 next if $old_hold->id eq $best_hold->id; # don't re-target the hold we want
2981                 $logger->info("circulator: clearing current_copy and prev_check_time on hold ".
2982             $old_hold->id." after a better hold [".$best_hold->id."] was found");
2983         $old_hold->clear_current_copy;
2984         $old_hold->clear_prev_check_time;
2985         $editor->update_action_hold_request($old_hold) 
2986             or return (undef, $editor->event);
2987         push(@retarget, $old_hold->id);
2988         }
2989
2990         return ($best_hold, undef, (@retarget) ? \@retarget : undef);
2991 }
2992
2993
2994
2995
2996
2997
2998 __PACKAGE__->register_method(
2999     method   => 'all_rec_holds',
3000     api_name => 'open-ils.circ.holds.retrieve_all_from_title',
3001 );
3002
3003 sub all_rec_holds {
3004         my( $self, $conn, $auth, $title_id, $args ) = @_;
3005
3006         my $e = new_editor(authtoken=>$auth);
3007         $e->checkauth or return $e->event;
3008         $e->allowed('VIEW_HOLD') or return $e->event;
3009
3010         $args ||= {};
3011     $args->{fulfillment_time} = undef; #  we don't want to see old fulfilled holds
3012         $args->{cancel_time} = undef;
3013
3014         my $resp = { volume_holds => [], copy_holds => [], recall_holds => [], force_holds => [], metarecord_holds => [], part_holds => [], issuance_holds => [] };
3015
3016     my $mr_map = $e->search_metabib_metarecord_source_map({source => $title_id})->[0];
3017     if($mr_map) {
3018         $resp->{metarecord_holds} = $e->search_action_hold_request(
3019             {   hold_type => OILS_HOLD_TYPE_METARECORD,
3020                 target => $mr_map->metarecord,
3021                 %$args 
3022             }, {idlist => 1}
3023         );
3024     }
3025
3026         $resp->{title_holds} = $e->search_action_hold_request(
3027                 { 
3028                         hold_type => OILS_HOLD_TYPE_TITLE, 
3029                         target => $title_id, 
3030                         %$args 
3031                 }, {idlist=>1} );
3032
3033     my $parts = $e->search_biblio_monograph_part(
3034         {
3035             record => $title_id
3036         }, {idlist=>1} );
3037
3038     if (@$parts) {
3039         $resp->{part_holds} = $e->search_action_hold_request(
3040             {
3041                 hold_type => OILS_HOLD_TYPE_MONOPART,
3042                 target => $parts,
3043                 %$args
3044             }, {idlist=>1} );
3045     }
3046
3047     my $subs = $e->search_serial_subscription(
3048         { record_entry => $title_id }, {idlist=>1});
3049
3050     if (@$subs) {
3051         my $issuances = $e->search_serial_issuance(
3052             {subscription => $subs}, {idlist=>1}
3053         );
3054
3055         if ($issuances) {
3056             $resp->{issuance_holds} = $e->search_action_hold_request(
3057                 {
3058                     hold_type => OILS_HOLD_TYPE_ISSUANCE,
3059                     target => $issuances,
3060                     %$args
3061                 }, {idlist=>1}
3062             );
3063         }
3064     }
3065
3066         my $vols = $e->search_asset_call_number(
3067                 { record => $title_id, deleted => 'f' }, {idlist=>1});
3068
3069         return $resp unless @$vols;
3070
3071         $resp->{volume_holds} = $e->search_action_hold_request(
3072                 { 
3073                         hold_type => OILS_HOLD_TYPE_VOLUME, 
3074                         target => $vols,
3075                         %$args }, 
3076                 {idlist=>1} );
3077
3078         my $copies = $e->search_asset_copy(
3079                 { call_number => $vols, deleted => 'f' }, {idlist=>1});
3080
3081         return $resp unless @$copies;
3082
3083         $resp->{copy_holds} = $e->search_action_hold_request(
3084                 { 
3085                         hold_type => OILS_HOLD_TYPE_COPY,
3086                         target => $copies,
3087                         %$args }, 
3088                 {idlist=>1} );
3089
3090         $resp->{recall_holds} = $e->search_action_hold_request(
3091                 { 
3092                         hold_type => OILS_HOLD_TYPE_RECALL,
3093                         target => $copies,
3094                         %$args }, 
3095                 {idlist=>1} );
3096
3097         $resp->{force_holds} = $e->search_action_hold_request(
3098                 { 
3099                         hold_type => OILS_HOLD_TYPE_FORCE,
3100                         target => $copies,
3101                         %$args }, 
3102                 {idlist=>1} );
3103
3104         return $resp;
3105 }
3106
3107
3108
3109
3110
3111 __PACKAGE__->register_method(
3112     method        => 'uber_hold',
3113     authoritative => 1,
3114     api_name      => 'open-ils.circ.hold.details.retrieve'
3115 );
3116
3117 sub uber_hold {
3118         my($self, $client, $auth, $hold_id, $args) = @_;
3119         my $e = new_editor(authtoken=>$auth);
3120         $e->checkauth or return $e->event;
3121     return uber_hold_impl($e, $hold_id, $args);
3122 }
3123
3124 __PACKAGE__->register_method(
3125     method        => 'batch_uber_hold',
3126     authoritative => 1,
3127     stream        => 1,
3128     api_name      => 'open-ils.circ.hold.details.batch.retrieve'
3129 );
3130
3131 sub batch_uber_hold {
3132         my($self, $client, $auth, $hold_ids, $args) = @_;
3133         my $e = new_editor(authtoken=>$auth);
3134         $e->checkauth or return $e->event;
3135     $client->respond(uber_hold_impl($e, $_, $args)) for @$hold_ids;
3136     return undef;
3137 }
3138
3139 sub uber_hold_impl {
3140     my($e, $hold_id, $args) = @_;
3141     $args ||= {};
3142
3143         my $hold = $e->retrieve_action_hold_request(
3144                 [
3145                         $hold_id,
3146                         {
3147                                 flesh => 1,
3148                                 flesh_fields => { ahr => [ 'current_copy', 'usr', 'notes' ] }
3149                         }
3150                 ]
3151         ) or return $e->event;
3152
3153     if($hold->usr->id ne $e->requestor->id) {
3154         # A user is allowed to see his/her own holds
3155             $e->allowed('VIEW_HOLD') or return $e->event;
3156         $hold->notes( # filter out any non-staff ("private") notes
3157             [ grep { !$U->is_true($_->staff) } @{$hold->notes} ] );
3158
3159     } else {
3160         # caller is asking for own hold, but may not have permission to view staff notes
3161             unless($e->allowed('VIEW_HOLD')) {
3162             $hold->notes( # filter out any staff notes
3163                 [ grep { $U->is_true($_->staff) } @{$hold->notes} ] );
3164         }
3165     }
3166
3167         my $user = $hold->usr;
3168         $hold->usr($user->id);
3169
3170
3171         my( $mvr, $volume, $copy, $issuance, $part, $bre ) = find_hold_mvr($e, $hold, $args->{suppress_mvr});
3172
3173         flesh_hold_notices([$hold], $e) unless $args->{suppress_notices};
3174         flesh_hold_transits([$hold]) unless $args->{suppress_transits};
3175
3176     my $details = retrieve_hold_queue_status_impl($e, $hold);
3177
3178     my $resp = {
3179         hold    => $hold,
3180         bre_id  => $bre->id,
3181         ($copy     ? (copy           => $copy)     : ()),
3182         ($volume   ? (volume         => $volume)   : ()),
3183         ($issuance ? (issuance       => $issuance) : ()),
3184         ($part     ? (part           => $part)     : ()),
3185         ($args->{include_bre}  ?  (bre => $bre)    : ()),
3186         ($args->{suppress_mvr} ?  () : (mvr => $mvr)),
3187         %$details
3188     };
3189
3190     unless($args->{suppress_patron_details}) {
3191             my $card = $e->retrieve_actor_card($user->card) or return $e->event;
3192         $resp->{patron_first}   = $user->first_given_name,
3193         $resp->{patron_last}    = $user->family_name,
3194         $resp->{patron_barcode} = $card->barcode,
3195         $resp->{patron_alias}   = $user->alias,
3196     };
3197
3198     return $resp;
3199 }
3200
3201
3202
3203 # -----------------------------------------------------
3204 # Returns the MVR object that represents what the
3205 # hold is all about
3206 # -----------------------------------------------------
3207 sub find_hold_mvr {
3208         my( $e, $hold, $no_mvr ) = @_;
3209
3210         my $tid;
3211         my $copy;
3212         my $volume;
3213     my $issuance;
3214     my $part;
3215
3216         if( $hold->hold_type eq OILS_HOLD_TYPE_METARECORD ) {
3217                 my $mr = $e->retrieve_metabib_metarecord($hold->target)
3218                         or return $e->event;
3219                 $tid = $mr->master_record;
3220
3221         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_TITLE ) {
3222                 $tid = $hold->target;
3223
3224         } elsif( $hold->hold_type eq OILS_HOLD_TYPE_VOLUME ) {
3225                 $volume = $e->retrieve_asset_call_number($hold->target)
3226                         or return $e->event;
3227                 $tid = $volume->record;
3228
3229     } elsif( $hold->hold_type eq OILS_HOLD_TYPE_ISSUANCE ) {
3230         $issuance = $e->retrieve_serial_issuance([
3231             $hold->target,
3232             {flesh => 1, flesh_fields => {siss => [ qw/subscription/ ]}}
3233         ]) or return $e->event;
3234
3235         $tid = $issuance->subscription->record_entry;
3236
3237     } elsif( $hold->hold_type eq OILS_HOLD_TYPE_MONOPART ) {
3238         $part = $e->retrieve_biblio_monograph_part([
3239             $hold->target
3240         ]) or return $e->event;
3241
3242         $tid = $part->record;
3243
3244         } 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 ) {
3245                 $copy = $e->retrieve_asset_copy([
3246             $hold->target, 
3247             {flesh => 1, flesh_fields => {acp => ['call_number']}}
3248         ]) or return $e->event;
3249         
3250                 $volume = $copy->call_number;
3251                 $tid = $volume->record;
3252         }
3253
3254         if(!$copy and ref $hold->current_copy ) {
3255                 $copy = $hold->current_copy;
3256                 $hold->current_copy($copy->id);
3257         }
3258
3259         if(!$volume and $copy) {
3260                 $volume = $e->retrieve_asset_call_number($copy->call_number);
3261         }
3262
3263     # TODO return metarcord mvr for M holds
3264         my $title = $e->retrieve_biblio_record_entry($tid);
3265         return ( ($no_mvr) ? undef : $U->record_to_mvr($title), $volume, $copy, $issuance, $part, $title );
3266 }
3267
3268 __PACKAGE__->register_method(
3269     method    => 'clear_shelf_cache',
3270     api_name  => 'open-ils.circ.hold.clear_shelf.get_cache',
3271     stream    => 1,
3272     signature => {
3273         desc => q/
3274             Returns the holds processed with the given cache key
3275         /
3276     }
3277 );
3278
3279 sub clear_shelf_cache {
3280     my($self, $client, $auth, $cache_key, $chunk_size) = @_;
3281     my $e = new_editor(authtoken => $auth, xact => 1);
3282     return $e->die_event unless $e->checkauth and $e->allowed('VIEW_HOLD');
3283
3284     $chunk_size ||= 25;
3285     my $hold_data = OpenSRF::Utils::Cache->new('global')->get_cache($cache_key);
3286
3287     if (!$hold_data) {
3288         $logger->info("no hold data found in cache"); # XXX TODO return event
3289         $e->rollback;
3290         return undef;
3291     }
3292
3293     my $maximum = 0;
3294     foreach (keys %$hold_data) {
3295         $maximum += scalar(@{ $hold_data->{$_} });
3296     }
3297     $client->respond({"maximum" => $maximum, "progress" => 0});
3298
3299     for my $action (sort keys %$hold_data) {
3300         while (@{$hold_data->{$action}}) {
3301             my @hid_chunk = splice @{$hold_data->{$action}}, 0, $chunk_size;
3302
3303             my $result_chunk = $e->json_query({
3304                 "select" => {
3305                     "acp" => ["barcode"],
3306                     "au" => [qw/
3307                         first_given_name second_given_name family_name alias
3308                     /],
3309                     "acn" => ["label"],
3310                     "acnp" => [{column => "label", alias => "prefix"}],
3311                     "acns" => [{column => "label", alias => "suffix"}],
3312                     "bre" => ["marc"],
3313                     "acpl" => ["name"],
3314                     "ahr" => ["id"]
3315                 },
3316                 "from" => {
3317                     "ahr" => {
3318                         "acp" => {
3319                             "field" => "id", "fkey" => "current_copy",
3320                             "join" => {
3321                                 "acn" => {
3322                                     "field" => "id", "fkey" => "call_number",
3323                                     "join" => {
3324                                         "bre" => {
3325                                             "field" => "id", "fkey" => "record"
3326                                         },
3327                                         "acnp" => {
3328                                             "field" => "id", "fkey" => "prefix"
3329                                         },
3330                                         "acns" => {
3331                                             "field" => "id", "fkey" => "suffix"
3332                                         }
3333                                     }
3334                                 },
3335                                 "acpl" => {"field" => "id", "fkey" => "location"}
3336                             }
3337                         },
3338                         "au" => {"field" => "id", "fkey" => "usr"}
3339                     }
3340                 },
3341                 "where" => {"+ahr" => {"id" => \@hid_chunk}}
3342             }, {"substream" => 1}) or return $e->die_event;
3343
3344             $client->respond([
3345                 map {
3346                     +{"action" => $action, "hold_details" => $_}
3347                 } @$result_chunk
3348             ]);
3349         }
3350     }
3351
3352     $e->rollback;
3353     return undef;
3354 }
3355
3356
3357 __PACKAGE__->register_method(
3358     method    => 'clear_shelf_process',
3359     stream    => 1,
3360     api_name  => 'open-ils.circ.hold.clear_shelf.process',
3361     signature => {
3362         desc => q/
3363             1. Find all holds that have expired on the holds shelf
3364             2. Cancel the holds
3365             3. If a clear-shelf status is configured, put targeted copies into this status
3366             4. Divide copies into 3 groups: items to transit, items to reshelve, and items
3367                 that are needed for holds.  No subsequent action is taken on the holds
3368                 or items after grouping.
3369         /
3370     }
3371 );
3372
3373 sub clear_shelf_process {
3374         my($self, $client, $auth, $org_id, $match_copy) = @_;
3375
3376         my $e = new_editor(authtoken=>$auth, xact => 1);
3377         $e->checkauth or return $e->die_event;
3378         my $cache = OpenSRF::Utils::Cache->new('global');
3379
3380     $org_id ||= $e->requestor->ws_ou;
3381         $e->allowed('UPDATE_HOLD', $org_id) or return $e->die_event;
3382
3383     my $copy_status = $U->ou_ancestor_setting_value($org_id, 'circ.holds.clear_shelf.copy_status');
3384
3385     my @hold_ids = $self->method_lookup(
3386         "open-ils.circ.captured_holds.id_list.expired_on_shelf.retrieve"
3387     )->run($auth, $org_id, $match_copy);
3388
3389     my @holds;
3390     my @canceled_holds; # newly canceled holds
3391     my $chunk_size = 25; # chunked status updates
3392     my $counter = 0;
3393     for my $hold_id (@hold_ids) {
3394
3395         $logger->info("Clear shelf processing hold $hold_id");
3396         
3397         my $hold = $e->retrieve_action_hold_request([
3398             $hold_id, {   
3399                 flesh => 1,
3400                 flesh_fields => {ahr => ['current_copy']}
3401             }
3402         ]);
3403
3404         if (!$hold->cancel_time) { # may be canceled but still on the holds shelf
3405             $hold->cancel_time('now');
3406             $hold->cancel_cause(2); # Hold Shelf expiration
3407             $e->update_action_hold_request($hold) or return $e->die_event;
3408             delete_hold_copy_maps($self, $e, $hold->id) and return $e->die_event;
3409             push(@canceled_holds, $hold_id);
3410         }
3411
3412         my $copy = $hold->current_copy;
3413
3414         if($copy_status or $copy_status == 0) {
3415             # if a clear-shelf copy status is defined, update the copy
3416             $copy->status($copy_status);
3417             $copy->edit_date('now');
3418             $copy->editor($e->requestor->id);
3419             $e->update_asset_copy($copy) or return $e->die_event;
3420         }
3421
3422         push(@holds, $hold);
3423         $client->respond({maximum => scalar(@holds), progress => $counter}) if ( (++$counter % $chunk_size) == 0);
3424     }
3425
3426     if ($e->commit) {
3427
3428         my %cache_data = (
3429             hold => [],
3430             transit => [],
3431             shelf => []
3432         );
3433
3434         for my $hold (@holds) {
3435
3436             my $copy = $hold->current_copy;
3437             my ($alt_hold) = __PACKAGE__->find_nearest_permitted_hold($e, $copy, $e->requestor, 1);
3438
3439             if($alt_hold and !$match_copy) {
3440
3441                 push(@{$cache_data{hold}}, $hold->id); # copy is needed for a hold
3442
3443             } elsif($copy->circ_lib != $e->requestor->ws_ou) {
3444
3445                 push(@{$cache_data{transit}}, $hold->id); # copy needs to transit
3446
3447             } else {
3448
3449                 push(@{$cache_data{shelf}}, $hold->id); # copy needs to go back to the shelf
3450             }
3451         }
3452
3453         my $cache_key = md5_hex(time . $$ . rand());
3454         $logger->info("clear_shelf_cache: storing under $cache_key");
3455         $cache->put_cache($cache_key, \%cache_data, 7200); # TODO: 2 hours.  configurable?
3456
3457         # tell the client we're done
3458         $client->respond_complete({cache_key => $cache_key});
3459
3460         # ------------
3461         # fire off the hold cancelation trigger and wait for response so don't flood the service
3462
3463         # refetch the holds to pick up the caclulated cancel_time, 
3464         # which may be needed by Action/Trigger
3465         $e->xact_begin;
3466         my $updated_holds = [];
3467         $updated_holds = $e->search_action_hold_request({id => \@canceled_holds}, {substream => 1}) if (@canceled_holds > 0);
3468         $e->rollback;
3469
3470         $U->create_events_for_hook(
3471             'hold_request.cancel.expire_holds_shelf', 
3472             $_, $org_id, undef, undef, 1) for @$updated_holds;
3473
3474     } else {
3475         # tell the client we're done
3476         $client->respond_complete;
3477     }
3478 }
3479
3480 __PACKAGE__->register_method(
3481     method    => 'usr_hold_summary',
3482     api_name  => 'open-ils.circ.holds.user_summary',
3483     signature => q/
3484         Returns a summary of holds statuses for a given user
3485     /
3486 );
3487
3488 sub usr_hold_summary {
3489     my($self, $conn, $auth, $user_id) = @_;
3490
3491         my $e = new_editor(authtoken=>$auth);
3492         $e->checkauth or return $e->event;
3493         $e->allowed('VIEW_HOLD') or return $e->event;
3494
3495     my $holds = $e->search_action_hold_request(
3496         {  
3497             usr =>  $user_id , 
3498             fulfillment_time => undef,
3499             cancel_time      => undef,
3500         }
3501     );
3502
3503     my %summary = (1 => 0, 2 => 0, 3 => 0, 4 => 0);
3504     $summary{_hold_status($e, $_)} += 1 for @$holds;
3505     return \%summary;
3506 }
3507
3508
3509
3510 __PACKAGE__->register_method(
3511     method    => 'hold_has_copy_at',
3512     api_name  => 'open-ils.circ.hold.has_copy_at',
3513     signature => {
3514         desc   => 
3515                 'Returns the ID of the found copy and name of the shelving location if there is ' .
3516                 'an available copy at the specified org unit.  Returns empty hash otherwise.  '   .
3517                 'The anticipated use for this method is to determine whether an item is '         .
3518                 'available at the library where the user is placing the hold (or, alternatively, '.
3519                 'at the pickup library) to encourage bypassing the hold placement and just '      .
3520                 'checking out the item.' ,
3521         params => [
3522             { desc => 'Authentication Token', type => 'string' },
3523             { desc => 'Method Arguments.  Options include: hold_type, hold_target, org_unit.  ' 
3524                     . 'hold_type is the hold type code (T, V, C, M, ...).  '
3525                     . 'hold_target is the identifier of the hold target object.  ' 
3526                     . 'org_unit is org unit ID.', 
3527               type => 'object' 
3528             }
3529         ],
3530         return => { 
3531             desc => q/Result hash like { "copy" : copy_id, "location" : location_name }, empty hash on misses, event on error./,
3532             type => 'object' 
3533         }
3534     }
3535 );
3536
3537 sub hold_has_copy_at {
3538     my($self, $conn, $auth, $args) = @_;
3539
3540         my $e = new_editor(authtoken=>$auth);
3541         $e->checkauth or return $e->event;
3542
3543     my $hold_type   = $$args{hold_type};
3544     my $hold_target = $$args{hold_target};
3545     my $org_unit    = $$args{org_unit};
3546
3547     my $query = {
3548         select => {acp => ['id'], acpl => ['name']},
3549         from   => {
3550             acp => {
3551                 acpl => {field => 'id', filter => { holdable => 't'}, fkey => 'location'},
3552                 ccs  => {field => 'id', filter => { holdable => 't'}, fkey => 'status'  }
3553             }
3554         },
3555         where => {'+acp' => { circulate => 't', deleted => 'f', holdable => 't', circ_lib => $org_unit, status => [0,7]}},
3556         limit => 1
3557     };
3558
3559     if($hold_type eq 'C' or $hold_type eq 'F' or $hold_type eq 'R') {
3560
3561         $query->{where}->{'+acp'}->{id} = $hold_target;
3562
3563     } elsif($hold_type eq 'V') {
3564
3565         $query->{where}->{'+acp'}->{call_number} = $hold_target;
3566
3567     } elsif($hold_type eq 'P') {
3568
3569         $query->{from}->{acp}->{acpm} = {
3570             field  => 'target_copy',
3571             fkey   => 'id',
3572             filter => {part => $hold_target},
3573         };
3574
3575     } elsif($hold_type eq 'I') {
3576
3577         $query->{from}->{acp}->{sitem} = {
3578             field  => 'unit',
3579             fkey   => 'id',
3580             filter => {issuance => $hold_target},
3581         };
3582
3583     } elsif($hold_type eq 'T') {
3584
3585         $query->{from}->{acp}->{acn} = {
3586             field  => 'id',
3587             fkey   => 'call_number',
3588             'join' => {
3589                 bre => {
3590                     field  => 'id',
3591                     filter => {id => $hold_target},
3592                     fkey   => 'record'
3593                 }
3594             }
3595         };
3596
3597     } else {
3598
3599         $query->{from}->{acp}->{acn} = {
3600             field => 'id',
3601             fkey  => 'call_number',
3602             join  => {
3603                 bre => {
3604                     field => 'id',
3605                     fkey  => 'record',
3606                     join  => {
3607                         mmrsm => {
3608                             field  => 'source',
3609                             fkey   => 'id',
3610                             filter => {metarecord => $hold_target},
3611                         }
3612                     }
3613                 }
3614             }
3615         };
3616     }
3617
3618     my $res = $e->json_query($query)->[0] or return {};
3619     return {copy => $res->{id}, location => $res->{name}} if $res;
3620 }
3621
3622
3623 # returns true if the user already has an item checked out 
3624 # that could be used to fulfill the requested hold.
3625 sub hold_item_is_checked_out {
3626     my($e, $user_id, $hold_type, $hold_target) = @_;
3627
3628     my $query = {
3629         select => {acp => ['id']},
3630         from   => {acp => {}},
3631         where  => {
3632             '+acp' => {
3633                 id => {
3634                     in => { # copies for circs the user has checked out
3635                         select => {circ => ['target_copy']},
3636                         from   => 'circ',
3637                         where  => {
3638                             usr => $user_id,
3639                             checkin_time => undef,
3640                             '-or' => [
3641                                 {stop_fines => ["MAXFINES","LONGOVERDUE"]},
3642                                 {stop_fines => undef}
3643                             ],
3644                         }
3645                     }
3646                 }
3647             }
3648         },
3649         limit => 1
3650     };
3651
3652     if($hold_type eq 'C' || $hold_type eq 'R' || $hold_type eq 'F') {
3653
3654         $query->{where}->{'+acp'}->{id}->{in}->{where}->{'target_copy'} = $hold_target;
3655
3656     } elsif($hold_type eq 'V') {
3657
3658         $query->{where}->{'+acp'}->{call_number} = $hold_target;
3659
3660      } elsif($hold_type eq 'P') {
3661
3662         $query->{from}->{acp}->{acpm} = {
3663             field  => 'target_copy',
3664             fkey   => 'id',
3665             filter => {part => $hold_target},
3666         };
3667
3668      } elsif($hold_type eq 'I') {
3669
3670         $query->{from}->{acp}->{sitem} = {
3671             field  => 'unit',
3672             fkey   => 'id',
3673             filter => {issuance => $hold_target},
3674         };
3675
3676     } elsif($hold_type eq 'T') {
3677
3678         $query->{from}->{acp}->{acn} = {
3679             field  => 'id',
3680             fkey   => 'call_number',
3681             'join' => {
3682                 bre => {
3683                     field  => 'id',
3684                     filter => {id => $hold_target},
3685                     fkey   => 'record'
3686                 }
3687             }
3688         };
3689
3690     } else {
3691
3692         $query->{from}->{acp}->{acn} = {
3693             field => 'id',
3694             fkey => 'call_number',
3695             join => {
3696                 bre => {
3697                     field => 'id',
3698                     fkey => 'record',
3699                     join => {
3700                         mmrsm => {
3701                             field => 'source',
3702                             fkey => 'id',
3703                             filter => {metarecord => $hold_target},
3704                         }
3705                     }
3706                 }
3707             }
3708         };
3709     }
3710
3711     return $e->json_query($query)->[0];
3712 }
3713
3714 __PACKAGE__->register_method(
3715     method    => 'change_hold_title',
3716     api_name  => 'open-ils.circ.hold.change_title',
3717     signature => {
3718         desc => q/
3719             Updates all title level holds targeting the specified bibs to point a new bib./,
3720         params => [
3721             { desc => 'Authentication Token', type => 'string' },
3722             { desc => 'New Target Bib Id',    type => 'number' },
3723             { desc => 'Old Target Bib Ids',   type => 'array'  },
3724         ],
3725         return => { desc => '1 on success' }
3726     }
3727 );
3728
3729 __PACKAGE__->register_method(
3730     method    => 'change_hold_title_for_specific_holds',
3731     api_name  => 'open-ils.circ.hold.change_title.specific_holds',
3732     signature => {
3733         desc => q/
3734             Updates specified holds to target new bib./,
3735         params => [
3736             { desc => 'Authentication Token', type => 'string' },
3737             { desc => 'New Target Bib Id',    type => 'number' },
3738             { desc => 'Holds Ids for holds to update',   type => 'array'  },
3739         ],
3740         return => { desc => '1 on success' }
3741     }
3742 );
3743
3744
3745 sub change_hold_title {
3746     my( $self, $client, $auth, $new_bib_id, $bib_ids ) = @_;
3747
3748     my $e = new_editor(authtoken=>$auth, xact=>1);
3749     return $e->die_event unless $e->checkauth;
3750
3751     my $holds = $e->search_action_hold_request(
3752         [
3753             {
3754                 cancel_time      => undef,
3755                 fulfillment_time => undef,
3756                 hold_type        => 'T',
3757                 target           => $bib_ids
3758             },
3759             {
3760                 flesh        => 1,
3761                 flesh_fields => { ahr => ['usr'] }
3762             }
3763         ],
3764         { substream => 1 }
3765     );
3766
3767     for my $hold (@$holds) {
3768         $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3769         $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3770         $hold->target( $new_bib_id );
3771         $e->update_action_hold_request($hold) or return $e->die_event;
3772     }
3773
3774     $e->commit;
3775
3776     _reset_hold($self, $e->requestor, $_) for @$holds;
3777
3778     return 1;
3779 }
3780
3781 sub change_hold_title_for_specific_holds {
3782     my( $self, $client, $auth, $new_bib_id, $hold_ids ) = @_;
3783
3784     my $e = new_editor(authtoken=>$auth, xact=>1);
3785     return $e->die_event unless $e->checkauth;
3786
3787     my $holds = $e->search_action_hold_request(
3788         [
3789             {
3790                 cancel_time      => undef,
3791                 fulfillment_time => undef,
3792                 hold_type        => 'T',
3793                 id               => $hold_ids
3794             },
3795             {
3796                 flesh        => 1,
3797                 flesh_fields => { ahr => ['usr'] }
3798             }
3799         ],
3800         { substream => 1 }
3801     );
3802
3803     for my $hold (@$holds) {
3804         $e->allowed('UPDATE_HOLD', $hold->usr->home_ou) or return $e->die_event;
3805         $logger->info("Changing hold " . $hold->id . " target from " . $hold->target . " to $new_bib_id in title hold target change");
3806         $hold->target( $new_bib_id );
3807         $e->update_action_hold_request($hold) or return $e->die_event;
3808     }
3809
3810     $e->commit;
3811
3812     _reset_hold($self, $e->requestor, $_) for @$holds;
3813
3814     return 1;
3815 }
3816
3817 __PACKAGE__->register_method(
3818     method    => 'rec_hold_count',
3819     api_name  => 'open-ils.circ.bre.holds.count',
3820     signature => {
3821         desc => q/Returns the total number of holds that target the 
3822             selected bib record or its associated copies and call_numbers/,
3823         params => [
3824             { desc => 'Bib ID', type => 'number' },
3825         ],
3826         return => {desc => 'Hold count', type => 'number'}
3827     }
3828 );
3829
3830 __PACKAGE__->register_method(
3831     method    => 'rec_hold_count',
3832     api_name  => 'open-ils.circ.mmr.holds.count',
3833     signature => {
3834         desc => q/Returns the total number of holds that target the 
3835             selected metarecord or its associated copies, call_numbers, and bib records/,
3836         params => [
3837             { desc => 'Metarecord ID', type => 'number' },
3838         ],
3839         return => {desc => 'Hold count', type => 'number'}
3840     }
3841 );
3842
3843 # XXX Need to add type I (and, soon, type P) holds to these counts
3844 sub rec_hold_count {
3845     my($self, $conn, $target_id) = @_;
3846
3847
3848     my $mmr_join = {
3849         mmrsm => {
3850             field => 'id',
3851             fkey => 'source',
3852             filter => {metarecord => $target_id}
3853         }
3854     };
3855
3856     my $bre_join = {
3857         bre => {
3858             field => 'id',
3859             filter => { id => $target_id },
3860             fkey => 'record'
3861         }
3862     };
3863
3864     if($self->api_name =~ /mmr/) {
3865         delete $bre_join->{bre}->{filter};
3866         $bre_join->{bre}->{join} = $mmr_join;
3867     }
3868
3869     my $cn_join = {
3870         acn => {
3871             field => 'id',
3872             fkey => 'call_number',
3873             join => $bre_join
3874         }
3875     };
3876
3877     my $query = {
3878         select => {ahr => [{column => 'id', transform => 'count', alias => 'count'}]},
3879         from => 'ahr',
3880         where => {
3881             '+ahr' => {
3882                 cancel_time => undef, 
3883                 fulfillment_time => undef,
3884                 '-or' => [
3885                     {
3886                         '-and' => {
3887                             hold_type => [qw/C F R/],
3888                             target => {
3889                                 in => {
3890                                     select => {acp => ['id']},
3891                                     from => { acp => $cn_join }
3892                                 }
3893                             }
3894                         }
3895                     },
3896                     {
3897                         '-and' => {
3898                             hold_type => 'V',
3899                             target => {
3900                                 in => {
3901                                     select => {acn => ['id']},
3902                                     from => {acn => $bre_join}
3903                                 }
3904                             }
3905                         }
3906                     },
3907                     {
3908                         '-and' => {
3909                             hold_type => 'T',
3910                             target => $target_id
3911                         }
3912                     }
3913                 ]
3914             }
3915         }
3916     };
3917
3918     if($self->api_name =~ /mmr/) {
3919         $query->{where}->{'+ahr'}->{'-or'}->[2] = {
3920             '-and' => {
3921                 hold_type => 'T',
3922                 target => {
3923                     in => {
3924                         select => {bre => ['id']},
3925                         from => {bre => $mmr_join}
3926                     }
3927                 }
3928             }
3929         };
3930
3931         $query->{where}->{'+ahr'}->{'-or'}->[3] = {
3932             '-and' => {
3933                 hold_type => 'M',
3934                 target => $target_id
3935             }
3936         };
3937     }
3938
3939
3940     return new_editor()->json_query($query)->[0]->{count};
3941 }
3942
3943
3944
3945
3946
3947
3948 1;