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