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