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