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