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