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