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