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