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