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