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