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