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