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