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