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