]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Utils/HoldTargeter.pm
LP#1596595 Targeter use child editor for settings
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Utils / HoldTargeter.pm
1 package OpenILS::Utils::HoldTargeter;
2 # ---------------------------------------------------------------
3 # Copyright (C) 2016 King County Library System
4 # Author: Bill Erickson <berickxx@gmail.com>
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 # ---------------------------------------------------------------
16 use strict;
17 use warnings;
18 use DateTime;
19 use OpenSRF::AppSession;
20 use OpenSRF::Utils::Logger qw(:logger);
21 use OpenSRF::Utils::JSON;
22 use OpenSRF::Utils qw/:datetime/;
23 use OpenILS::Application::AppUtils;
24 use OpenILS::Utils::CStoreEditor qw/:funcs/;
25
26 our $U = "OpenILS::Application::AppUtils";
27 our $dt_parser = DateTime::Format::ISO8601->new;
28
29 # See target() for runtime arguments.
30 sub new {
31     my ($class, %args) = @_;
32     my $self = {
33         editor => new_editor(),
34         ou_setting_cache => {},
35         %args,
36     };
37     return bless($self, $class);
38 }
39
40 # Target and retarget holds.
41 # By default, targets all holds that need targeting, meaning those that
42 # have either never been targeted or those whose prev_check_time exceeds
43 # the retarget interval.
44 #
45 # Returns an array of targeter response objects, one entry per hold
46 # targeted.  See also return_count.
47 #
48 # Optional parameters:
49 #
50 # hold => <id> / [<id>, <id>, ...]
51 #  (Re)target one or more specific holds.  Specified as a single hold ID
52 #  or an array ref of hold IDs.
53 #
54 # return_count => 1
55 #   Return the total number of holds processed instead of a result
56 #   object for every targeted hold.  Ideal for large batch targeting.
57 #
58 # retarget_interval => <interval string>
59 #   Override the 'circ.holds.retarget_interval' global_flag value.
60 #
61 # newest_first => 1
62 #   Target holds in reverse order of create_time. 
63 #
64 # skip_viable => 1
65 #   Avoid retargeting holds whose current_copy is still viable and
66 #   permitted.  This is useful for repairing holds whose targeted copy
67 #   has become non-viable for a given hold because its status changed or
68 #   policies affecting the hold/copy no longer allow it to be targeted.
69 #   This setting can be used in conjunction with any other settings.
70 #
71 # target_all => 1
72 #   USE WITH CAUTION.  Forces (re)targeting of all active holds.  This
73 #   is primarily useful or testing.
74 #
75 # parallel_count => n
76 #   Number of parallel targeters running.  This acts as the indication
77 #   that other targeter instances are running.
78 #
79 # parallel_slot => n [starts at 1]
80 #   Sets the parallel targeter instance position/slot.  Used to determine
81 #   which holds to process to avoid conflicts with other running instances.
82 #
83 sub target {
84     my ($self, %args) = @_;
85
86     $self->{$_} = $args{$_} for keys %args;
87
88     $self->init;
89
90     my $count = 0;
91     my @responses;
92
93     for my $hold_id ($self->find_holds_to_target) {
94         my $single = OpenILS::Utils::HoldTargeter::Single->new(
95             parent => $self,
96             skip_viable => $args{skip_viable}
97         );
98         $single->target($hold_id);
99         push(@responses, $single->result) unless $self->{return_count};
100         $count++;
101     }
102
103     return $self->{return_count} ? $count : \@responses;
104 }
105
106 sub find_holds_to_target {
107     my $self = shift;
108
109     if ($self->{hold}) {
110         # $self->{hold} can be a single hold ID or an array ref of hold IDs
111         return @{$self->{hold}} if ref $self->{hold} eq 'ARRAY';
112         return ($self->{hold});
113     }
114
115     my $query = {
116         select => {ahr => ['id']},
117         from => 'ahr',
118         where => {
119             capture_time => undef,
120             fulfillment_time => undef,
121             cancel_time => undef,
122             frozen => 'f'
123         },
124         order_by => [
125             {class => 'ahr', field => 'selection_depth', direction => 'DESC'},
126             {class => 'ahr', field => 'request_time'},
127             {class => 'ahr', field => 'prev_check_time'}
128         ]
129     };
130
131     if (!$self->{target_all}) {
132         # Unless we're retargeting all holds, limit to holds that have no
133         # prev_check_time or those whose prev_check_time occurred
134         # before the retarget interval.
135
136         my $date = DateTime->now->subtract(
137             seconds => $self->{retarget_interval});
138
139         $query->{where}->{'-or'} = [
140             {prev_check_time => undef},
141             {prev_check_time => {'<=' => $date->strftime('%F %T%z')}}
142         ];
143     }
144
145     # parallel < 1 means no parallel
146     my $parallel = ($self->{parallel_count} || 0) > 1 ? 
147         $self->{parallel_count} : 0;
148
149     if ($parallel) {
150         # In parallel mode, we need to also grab the metarecord for each hold.
151         $query->{from} = {
152             ahr => {
153                 rhrr => {
154                     fkey => 'id',
155                     field => 'id',
156                     join => {
157                         mmrsm => {
158                             field => 'source',
159                             fkey => 'bib_record'
160                         }
161                     }
162                 }
163             }
164         };
165
166         # In parallel mode, only process holds within the current process
167         # whose metarecord ID modulo the parallel targeter count matches
168         # our paralell targeting slot.  This ensures that no 2 processes
169         # will be operating on the same potential copy sets.
170         #
171         # E.g. Running 5 parallel and we are slot 3 (0-based slot 2) of 5, 
172         # process holds whose metarecord ID's are 2, 7, 12, 17, ...
173         # WHERE MOD(mmrsm.id, 5) = 2
174
175         # Slots are 1-based at the API level, but 0-based for modulo.
176         my $slot = $self->{parallel_slot} - 1;
177
178         $query->{where}->{'+mmrsm'} = {
179             id => {
180                 '=' => {
181                     transform => 'mod',
182                     value => $slot,
183                     params => [$parallel]
184                 }
185             }
186         };
187     }
188
189     # Newest-first sorting cares only about hold create_time.
190     $query->{order_by} =
191         [{class => 'ahr', field => 'request_time', direction => 'DESC'}]
192         if $self->{newest_first};
193
194     my $holds = $self->editor->json_query($query, {substream => 1});
195
196     return map {$_->{id}} @$holds;
197 }
198
199 sub editor {
200     my $self = shift;
201     return $self->{editor};
202 }
203
204 # Load startup data required by all targeter actions.
205 sub init {
206     my $self = shift;
207     my $e = $self->editor;
208
209     my $closed_orgs_query = {
210         close_start => {'<=', 'now'},
211         close_end => {'>=', 'now'}
212     };
213
214     if (!$self->{target_all}) {
215
216         # See if the caller provided an interval
217         my $interval = $self->{retarget_interval};
218
219         if (!$interval) {
220             # See if we have a global flag value for the interval
221
222             $interval = $e->search_config_global_flag({
223                 name => 'circ.holds.retarget_interval',
224                 enabled => 't'
225             })->[0];
226
227             # If no flag is present, default to a 24-hour retarget interval.
228             $interval = $interval ? $interval->value : '24h';
229         }
230
231         # Convert the interval to seconds for current and future use.
232         $self->{retarget_interval} = interval_to_seconds($interval);
233
234         # An org unit is considered closed for retargeting purposes
235         # if it's closed both now and at the next re-target date.
236
237         my $next_check_time =
238             DateTime->now->add(seconds => $self->{retarget_interval})
239             ->strftime('%F %T%z');
240
241         $closed_orgs_query = {
242             '-and' => [
243                 $closed_orgs_query, {
244                     close_start => {'<=', $next_check_time},
245                     close_end => {'>=', $next_check_time}
246                 }
247             ]
248         }
249     }
250
251     my $closed =
252         $self->editor->search_actor_org_unit_closed_date($closed_orgs_query);
253
254     # Map of org id to 1. Any org in the map is closed.
255     $self->{closed_orgs} = {map {$_->org_unit => 1} @$closed};
256 }
257
258 # Org unit setting fetch+cache
259 # $e is the OpenILS::Utils::HoldTargeter::Single editor.  Use it if
260 # provided to avoid timeouts on the in-transaction child editor.
261 sub get_ou_setting {
262     my ($self, $org_id, $setting, $e) = @_;
263     my $c = $self->{ou_setting_cache};
264
265     $e ||= $self->{editor};
266     $c->{$org_id} = {} unless $c->{$org_id};
267
268     $c->{$org_id}->{$setting} =
269         $U->ou_ancestor_setting_value($org_id, $setting, $e)
270         unless exists $c->{$org_id}->{$setting};
271
272     return $c->{$org_id}->{$setting};
273 }
274
275 # -----------------------------------------------------------------------
276 # Knows how to target a single hold.
277 # -----------------------------------------------------------------------
278 package OpenILS::Utils::HoldTargeter::Single;
279 use strict;
280 use warnings;
281 use DateTime;
282 use OpenSRF::AppSession;
283 use OpenSRF::Utils qw/:datetime/;
284 use OpenSRF::Utils::Logger qw(:logger);
285 use OpenILS::Application::AppUtils;
286 use OpenILS::Utils::CStoreEditor qw/:funcs/;
287
288 sub new {
289     my ($class, %args) = @_;
290     my $self = {
291         %args,
292         editor => new_editor(),
293         error => 0,
294         success => 0
295     };
296     return bless($self, $class);
297 }
298
299 # Parent targeter object.
300 sub parent {
301     my ($self, $parent) = @_;
302     $self->{parent} = $parent if $parent;
303     return $self->{parent};
304 }
305
306 sub hold_id {
307     my ($self, $hold_id) = @_;
308     $self->{hold_id} = $hold_id if $hold_id;
309     return $self->{hold_id};
310 }
311
312 sub hold {
313     my ($self, $hold) = @_;
314     $self->{hold} = $hold if $hold;
315     return $self->{hold};
316 }
317
318 # Debug message
319 sub message {
320     my ($self, $message) = @_;
321     $self->{message} = $message if $message;
322     return $self->{message} || '';
323 }
324
325 # True if the hold was successfully targeted.
326 sub success {
327     my ($self, $success) = @_;
328     $self->{success} = $success if defined $success;
329     return $self->{success};
330 }
331
332 # True if targeting exited early on an unrecoverable error.
333 sub error {
334     my ($self, $error) = @_;
335     $self->{error} = $error if defined $error;
336     return $self->{error};
337 }
338
339 sub editor {
340     my $self = shift;
341     return $self->{editor};
342 }
343
344 sub result {
345     my $self = shift;
346
347     return {
348         hold    => $self->hold_id,
349         error   => $self->error,
350         success => $self->success,
351         message => $self->message,
352         target  => $self->hold ? $self->hold->current_copy : undef,
353         old_target => $self->{previous_copy_id},
354         found_copy => $self->{found_copy},
355         eligible_copies => $self->{eligible_copy_count}
356     };
357 }
358
359 # List of potential copies in the form of slim hashes.  This list
360 # evolves as copies are filtered as they are deemed non-targetable.
361 sub copies {
362     my ($self, $copies) = @_;
363     $self->{copies} = $copies if $copies;
364     return $self->{copies};
365 }
366
367 # Final set of potential copies, including those that may not be
368 # currently targetable, that may be eligible for recall processing.
369 sub recall_copies {
370     my ($self, $recall_copies) = @_;
371     $self->{recall_copies} = $recall_copies if $recall_copies;
372     return $self->{recall_copies};
373 }
374
375 # Maps copy ID's to their hold proximity
376 sub copy_prox_map {
377     my ($self, $copy_prox_map) = @_;
378     $self->{copy_prox_map} = $copy_prox_map if $copy_prox_map;
379     return $self->{copy_prox_map};
380 }
381
382 sub log_hold {
383     my ($self, $msg, $err) = @_;
384     my $level = $err ? 'error' : 'info';
385     $logger->$level("targeter: [hold ".$self->hold_id."] $msg");
386 }
387
388 # Captures the exit message, rolls back the cstore transaction/connection,
389 # and returns false.
390 # is_error : log the final message and editor event at ERR level.
391 sub exit_targeter {
392     my ($self, $msg, $is_error) = @_;
393
394     $self->message($msg);
395     my $log = "exiting => $msg";
396
397     if ($is_error) {
398         # On error, roll back and capture the last editor event for logging.
399
400         my $evt = $self->editor->die_event;
401         $log .= " [".$evt->{textcode}."]" if $evt;
402
403         $self->error(1);
404         $self->log_hold($log, 1);
405
406     } else {
407         # Attempt a rollback and disconnect when each hold exits
408         # to avoid the possibility of leaving cstore's pinned.
409         # Note: ->rollback is a no-op when a ->commit has already occured.
410
411         $self->editor->rollback;
412         $self->log_hold($log);
413     }
414
415     return 0;
416 }
417
418 # Cancel expired holds and kick off the A/T no-target event.  Returns
419 # true (i.e. keep going) if the hold is not expired.  Returns false if
420 # the hold is canceled or a non-recoverable error occcurred.
421 sub handle_expired_hold {
422     my $self = shift;
423     my $hold = $self->hold;
424
425     return 1 unless $hold->expire_time;
426
427     my $ex_time =
428         $dt_parser->parse_datetime(cleanse_ISO8601($hold->expire_time));
429     return 1 unless DateTime->compare($ex_time, DateTime->now) < 0;
430
431     # Hold is expired --
432
433     $hold->cancel_time('now');
434     $hold->cancel_cause(1); # == un-targeted expiration
435
436     $self->editor->update_action_hold_request($hold)
437         or return $self->exit_targeter("Error canceling hold", 1);
438
439     $self->editor->commit;
440
441     # Fire the A/T handler, but don't wait for a response.
442     OpenSRF::AppSession->create('open-ils.trigger')->request(
443         'open-ils.trigger.event.autocreate',
444         'hold_request.cancel.expire_no_target',
445         $hold, $hold->pickup_lib
446     );
447
448     return $self->exit_targeter("Hold is expired");
449 }
450
451 # Find potential copies for hold mapping and targeting.
452 sub get_hold_copies {
453     my $self = shift;
454     my $e = $self->editor;
455     my $hold = $self->hold;
456
457     my $hold_target = $hold->target;
458     my $hold_type   = $hold->hold_type;
459     my $org_unit    = $hold->selection_ou;
460     my $org_depth   = $hold->selection_depth || 0;
461
462     my $query = {
463         select => {
464             acp => ['id', 'status', 'circ_lib'],
465             ahr => ['current_copy']
466         },
467         from => {
468             acp => {
469                 # Tag copies that are in use by other holds so we don't
470                 # try to target them for our hold.
471                 ahr => {
472                     type => 'left',
473                     fkey => 'id', # acp.id
474                     field => 'current_copy',
475                     filter => {
476                         fulfillment_time => undef,
477                         cancel_time => undef,
478                         id => {'!=' => $self->hold_id}
479                     }
480                 }
481             }
482         },
483         where => {
484             '+acp' => {
485                 deleted => 'f',
486                 circ_lib => {
487                     in => {
488                         select => {
489                             aou => [{
490                                 transform => 'actor.org_unit_descendants',
491                                 column => 'id',
492                                 result_field => 'id',
493                                 params => [$org_depth]
494                             }],
495                             },
496                         from => 'aou',
497                         where => {id => $org_unit}
498                     }
499                 }
500             }
501         }
502     };
503
504     unless ($hold_type eq 'R' || $hold_type eq 'F') {
505         # Add the holdability filters to the copy query, unless
506         # we're processing a Recall or Force hold, which bypass most
507         # holdability checks.
508
509         $query->{from}->{acp}->{acpl} = {
510             field => 'id',
511             filter => {holdable => 't', deleted => 'f'},
512             fkey => 'location'
513         };
514
515         $query->{from}->{acp}->{ccs} = {
516             field => 'id',
517             filter => {holdable => 't'},
518             fkey => 'status'
519         };
520
521         $query->{where}->{'+acp'}->{holdable} = 't';
522         $query->{where}->{'+acp'}->{mint_condition} = 't'
523             if $U->is_true($hold->mint_condition);
524     }
525
526     unless ($hold_type eq 'C' || $hold_type eq 'I' || $hold_type eq 'P') {
527         # For volume and higher level holds, avoid targeting copies that
528         # act as instances of monograph parts.
529         $query->{from}->{acp}->{acpm} = {
530             type => 'left',
531             field => 'target_copy',
532             fkey => 'id'
533         };
534
535         $query->{where}->{'+acpm'}->{id} = undef;
536     }
537
538     if ($hold_type eq 'C' || $hold_type eq 'R' || $hold_type eq 'F') {
539
540         $query->{where}->{'+acp'}->{id} = $hold_target;
541
542     } elsif ($hold_type eq 'V') {
543
544         $query->{where}->{'+acp'}->{call_number} = $hold_target;
545
546     } elsif ($hold_type eq 'P') {
547
548         $query->{from}->{acp}->{acpm} = {
549             field  => 'target_copy',
550             fkey   => 'id',
551             filter => {part => $hold_target},
552         };
553
554     } elsif ($hold_type eq 'I') {
555
556         $query->{from}->{acp}->{sitem} = {
557             field  => 'unit',
558             fkey   => 'id',
559             filter => {issuance => $hold_target},
560         };
561
562     } elsif ($hold_type eq 'T') {
563
564         $query->{from}->{acp}->{acn} = {
565             field  => 'id',
566             fkey   => 'call_number',
567             'join' => {
568                 bre => {
569                     field  => 'id',
570                     filter => {id => $hold_target},
571                     fkey   => 'record'
572                 }
573             }
574         };
575
576     } else { # Metarecord hold
577
578         $query->{from}->{acp}->{acn} = {
579             field => 'id',
580             fkey  => 'call_number',
581             join  => {
582                 bre => {
583                     field => 'id',
584                     fkey  => 'record',
585                     join  => {
586                         mmrsm => {
587                             field  => 'source',
588                             fkey   => 'id',
589                             filter => {metarecord => $hold_target},
590                         }
591                     }
592                 }
593             }
594         };
595
596         if ($hold->holdable_formats) {
597             # Compile the JSON-encoded metarecord holdable formats
598             # to an Intarray query_int string.
599             my $query_int = $e->json_query({
600                 from => [
601                     'metabib.compile_composite_attr',
602                     $hold->holdable_formats
603                 ]
604             })->[0];
605             # TODO: ^- any way to add this as a filter in the main query?
606
607             if ($query_int) {
608                 # Only pull potential copies from records that satisfy
609                 # the holdable formats query.
610                 my $qint = $query_int->{'metabib.compile_composite_attr'};
611                 $query->{from}->{acp}->{acn}->{join}->{bre}->{join}->{mravl} = {
612                     field  => 'source',
613                     fkey   => 'id',
614                     filter => {vlist => {'@@' => $qint}}
615                 }
616             }
617         }
618     }
619
620     my $copies = $e->json_query($query);
621     $self->{eligible_copy_count} = scalar(@$copies);
622
623     $self->log_hold($self->{eligible_copy_count}." potential copies");
624
625     # Let the caller know we encountered the copy they were interested in.
626     $self->{found_copy} = 1 if $self->{find_copy}
627         && grep {$_->{id} eq $self->{find_copy}} @$copies;
628
629     $self->copies($copies);
630
631     return 1;
632 }
633
634 # Delete and rebuild copy maps
635 sub update_copy_maps {
636     my $self = shift;
637     my $e = $self->editor;
638
639     my $resp = $e->json_query({from => [
640         'action.hold_request_regen_copy_maps',
641         $self->hold_id,
642         '{' . join(',', map {$_->{id}} @{$self->copies}) . '}'
643     ]});
644
645     # The above call can fail if another process is updating
646     # copy maps for this hold at the same time.
647     return 1 if $resp && @$resp;
648
649     return $self->exit_targeter("Error creating hold copy maps", 1);
650 }
651
652 # Returns a map of proximity values to arrays of copy hashes.
653 # The copy hash arrays are weighted consistent with the org unit hold
654 # target weight, meaning that a given copy may appear more than once
655 # in its proximity list.
656 sub compile_weighted_proximity_map {
657     my $self = shift;
658
659     # Collect copy proximity info (generated via DB trigger)
660     # from our newly create copy maps.
661     my $hold_copy_maps = $self->editor->json_query({
662         select => {ahcm => ['target_copy', 'proximity']},
663         from => 'ahcm',
664         where => {hold => $self->hold_id}
665     });
666
667     my %copy_prox_map =
668         map {$_->{target_copy} => $_->{proximity}} @$hold_copy_maps;
669
670     my %prox_map;
671     for my $copy_hash (@{$self->copies}) {
672         my $prox = $copy_prox_map{$copy_hash->{id}};
673         $prox_map{$prox} ||= [];
674
675         my $weight = $self->parent->get_ou_setting(
676             $copy_hash->{circ_lib},
677             'circ.holds.org_unit_target_weight', $self->editor) || 1;
678
679         # Each copy is added to the list once per target weight.
680         push(@{$prox_map{$prox}}, $copy_hash) foreach (1 .. $weight);
681     }
682
683     return $self->{weighted_prox_map} = \%prox_map;
684 }
685
686 # Returns true if filtering completed without error, false otherwise.
687 sub filter_closed_date_copies {
688     my $self = shift;
689
690     my @filtered_copies;
691     for my $copy_hash (@{$self->copies}) {
692         my $clib = $copy_hash->{circ_lib};
693
694         if ($self->parent->{closed_orgs}->{$clib}) {
695             # Org unit is currently closed.  See if it matters.
696
697             my $ous = $self->hold->pickup_lib eq $clib ?
698                 'circ.holds.target_when_closed_if_at_pickup_lib' :
699                 'circ.holds.target_when_closed';
700
701             unless (
702                 $self->parent->get_ou_setting($clib, $ous, $self->editor)) {
703                 # Targeting not allowed at this circ lib when its closed
704
705                 $self->log_hold("skipping copy ".
706                     $copy_hash->{id}."at closed org $clib");
707
708                 next;
709             }
710
711         }
712
713         push(@filtered_copies, $copy_hash);
714     }
715
716     # Update our in-progress list of copies to reflect the filtered set.
717     $self->copies(\@filtered_copies);
718
719     return 1;
720 }
721
722 # Limit the set of potential copies to those that are
723 # in a targetable status.
724 # Returns true if filtering completes without error, false otherwise.
725 sub filter_copies_by_status {
726     my $self = shift;
727
728     $self->copies([
729         grep {$_->{status} == 0 || $_->{status} == 7} @{$self->copies}
730     ]);
731
732     # Track checked out copies for later recall
733     $self->recall_copies([grep {$_->{status} == 1} @{$self->copies}]);
734
735     return 1;
736 }
737
738 # Remove copies that are currently targeted by other holds.
739 # Returns true if filtering completes without error, false otherwise.
740 sub filter_copies_in_use {
741     my $self = shift;
742
743     # A copy with a 'current_copy' value means it's in use by another hold.
744     $self->copies([
745         grep {!$_->{current_copy}} @{$self->copies}
746     ]);
747
748     return 1;
749 }
750
751 # Returns true if inspection completed without error, false otherwise.
752 sub inspect_previous_target {
753     my $self = shift;
754     my $hold = $self->hold;
755     my @copies = @{$self->copies};
756
757     # no previous target
758     return 1 unless my $prev_id = $hold->current_copy;
759
760     $self->{previous_copy_id} = $prev_id;
761
762     # See if the previous copy is in our list of valid copies.
763     my ($prev) = grep {$_->{id} eq $prev_id} @copies;
764
765     # exit if previous target is no longer valid.
766     return 1 unless $prev;
767
768     if ($self->{skip_viable}) {
769         # In skip_viable mode, leave the hold as-is if the existing
770         # current_copy is still permitted.
771         # Note: viability checking is done this late in the process
772         # (specifically after other potential copies have been fetched)
773         # because we first need to confirm the current_copy is a valid
774         # potential copy (e.g. it's holdable, non-deleted, etc.), which
775         # copy_is_permitted, which only checks hold matrix policies,
776         # does not check.
777
778         return $self->exit_targeter("Skipping with viable target = $prev_id")
779             if $self->copy_is_permitted($prev);
780
781         # Previous copy is now confirmed non-viable.
782
783     } else {
784
785         # Previous copy may be targetable.  Keep it around for later
786         # in case we need to confirm its viability and re-use it.
787         $self->{valid_previous_copy} = $prev;
788     }
789
790     # Remove the previous copy from the working set of potential copies.
791     # It will be revisited later if needed.
792     $self->copies([grep {$_->{id} ne $prev_id} @copies]);
793
794     return 1;
795 }
796
797 # Returns true if we have at least one potential copy remaining, thus
798 # targeting should continue.  Otherwise, the hold is updated to reflect
799 # that there is no target and returns false to stop targeting.
800 sub handle_no_copies {
801     my ($self, %args) = @_;
802
803     if (!$args{force}) {
804         # If 'force' is set, the caller is saying that all copies have
805         # failed.  Otherwise, see if we have any copies left to inspect.
806         return 1 if @{$self->copies} || $self->{valid_previous_copy};
807     }
808
809     # At this point, all copies have been inspected and none
810     # have yielded a targetable item.
811
812     if ($args{process_recalls}) {
813         # See if we have any copies/circs to recall.
814         return unless $self->process_recalls;
815     }
816
817     my $hold = $self->hold;
818     $hold->clear_current_copy;
819     $hold->prev_check_time('now');
820
821     $self->editor->update_action_hold_request($hold)
822         or return $self->exit_targeter("Error updating hold request", 1);
823
824     $self->editor->commit;
825     return $self->exit_targeter("Hold has no targetable copies");
826 }
827
828 # Force and recall holds bypass validity tests.  Returns the first
829 # (and presumably only) copy in our list of valid copies when a
830 # F or R hold is encountered.  Returns undef otherwise.
831 sub attempt_force_recall_target {
832     my $self = shift;
833     return $self->copies->[0] if
834         $self->hold->hold_type eq 'R' || $self->hold->hold_type eq 'F';
835     return undef;
836 }
837
838 sub attempt_to_find_copy {
839     my $self = shift;
840
841     return undef unless @{$self->copies};
842
843     my $max_loops = $self->parent->get_ou_setting(
844         $self->hold->pickup_lib,
845         'circ.holds.max_org_unit_target_loops',
846         $self->editor
847     );
848
849     return $self->target_by_org_loops($max_loops) if $max_loops;
850
851     # When not using target loops, targeting is based solely on
852     # proximity and org unit target weight.
853     $self->compile_weighted_proximity_map;
854
855     return $self->find_nearest_copy;
856 }
857
858 # Returns 2 arrays.  The first is a list of copies whose circ lib's
859 # unfulfilled target count matches the provided $iter value.  The 
860 # second list is all other copies, returned for convenience.
861 sub get_copies_at_loop_iter {
862     my ($self, $targeted_libs, $iter) = @_;
863
864     my @iter_copies; # copies to try now.
865     my @remaining_copies; # copies to try later
866
867     for my $copy (@{$self->copies}) {
868         my $match = 0;
869
870         if ($iter == 0) {
871             # Start with copies at circ libs that have never been targeted.
872             $match = 1 unless grep {
873                 $copy->{circ_lib} eq $_->{circ_lib}} @$targeted_libs;
874
875         } else {
876             # Find copies at branches whose target count
877             # matches the current (non-zero) loop depth.
878
879             $match = 1 if grep {
880                 $_->{count} eq $iter &&
881                 $_->{circ_lib} eq $copy->{circ_lib}
882             } @$targeted_libs;
883         }
884
885         if ($match) {
886             push(@iter_copies, $copy);
887         } else {
888             push(@remaining_copies, $copy);
889         }
890     }
891
892     $self->log_hold(
893         sprintf("%d potential copies at max-loops iteration level $iter. ".
894             "%d remain to be tested at a higher loop iteration level.",
895             scalar(@iter_copies), 
896             scalar(@remaining_copies)
897         )
898     );
899
900     return (\@iter_copies, \@remaining_copies);
901 }
902
903 # Find libs whose unfulfilled target count is less than the maximum
904 # configured loop count.  Target copies in order of their circ_lib's
905 # target count (starting at 0) and moving up.  Copies within each
906 # loop count group are weighted based on configured hold weight.  If
907 # no copies in a given group are targetable, move up to the next
908 # unfulfilled target level.  Keep doing this until all potential
909 # copies have been tried or max targets loops is exceeded.
910 # Returns a targetable copy if one is found, undef otherwise.
911 sub target_by_org_loops {
912     my ($self, $max_loops) = @_;
913
914     my $targeted_libs = $self->editor->json_query({
915         select => {aufhl => ['circ_lib', 'count']},
916         from => 'aufhl',
917         where => {hold => $self->hold_id},
918         order_by => [{class => 'aufhl', field => 'count'}]
919     });
920
921     my $max_tried = 0; # Highest per-lib target attempts.
922     foreach (@$targeted_libs) {
923         $max_tried = $_->{count} if $_->{count} > $max_tried;
924     }
925
926     $self->log_hold("Max lib attempts is $max_tried. ".
927         scalar(@$targeted_libs)." libs have been targeted at least once.");
928
929     # $loop_iter represents per-lib target attemtps already made.
930     # When loop_iter equals max loops, all libs with targetable copies
931     # have been targeted the maximum number of times.  loop_iter starts
932     # at 0 to pick up libs that have never been targeted.
933     my $loop_iter = -1;
934     while (++$loop_iter < $max_loops) {
935
936         # Ran out of copies to try before exceeding max target loops.
937         # Nothing else to do here.
938         return undef unless @{$self->copies};
939
940         my ($iter_copies, $remaining_copies) = 
941             $self->get_copies_at_loop_iter($targeted_libs, $loop_iter);
942
943         next unless @$iter_copies;
944
945         $self->copies($iter_copies);
946
947         # Update the proximity map to only include the copies
948         # from this loop-depth iteration.
949         $self->compile_weighted_proximity_map;
950
951         my $copy = $self->find_nearest_copy;
952         return $copy if $copy; # found one!
953
954         # No targetable copy at the current target loop.
955         # Update our current copy set to the not-yet-tested copies.
956         $self->copies($remaining_copies);
957     }
958
959     # Avoid canceling the hold with exceeds-loops unless at least one
960     # lib has been targeted max_loops times.  Otherwise, the hold goes
961     # back to waiting for another copy (or retargets its current copy).
962     return undef if $max_tried < $max_loops;
963
964     # At least one lib has been targeted max-loops times and zero 
965     # other copies are targetable.  All options have been exhausted.
966     return $self->handle_exceeds_target_loops;
967 }
968
969 # Cancel the hold, fire the no-target A/T event handler, and exit.
970 sub handle_exceeds_target_loops {
971     my $self = shift;
972     my $e = $self->editor;
973     my $hold = $self->hold;
974
975     $hold->cancel_time('now');
976     $hold->cancel_cause(1); # = un-targeted expiration
977
978     $e->update_action_hold_request($hold)
979         or return $self->exit_targeter("Error updating hold request", 1);
980
981     $e->commit;
982
983     # Fire the A/T handler, but don't wait for a response.
984     OpenSRF::AppSession->create('open-ils.trigger')->request(
985         'open-ils.trigger.event.autocreate',
986         'hold_request.cancel.expire_no_target',
987         $hold, $hold->pickup_lib
988     );
989
990     return $self->exit_targeter("Hold exceeded max target loops");
991 }
992
993 # When all else fails, see if we can reuse the previously targeted copy.
994 sub attempt_prev_copy_retarget {
995     my $self = shift;
996
997     # earlier target logic can in some cases cancel the hold.
998     return undef if $self->hold->cancel_time;
999
1000     my $prev_copy = $self->{valid_previous_copy};
1001     return undef unless $prev_copy;
1002
1003     $self->log_hold("attempting to re-target previously ".
1004         "targeted copy for hold ".$self->hold_id);
1005
1006     if ($self->copy_is_permitted($prev_copy)) {
1007         $self->log_hold("retargeting the previously ".
1008             "targeted copy [".$prev_copy->{id}."]" );
1009         return $prev_copy;
1010     }
1011
1012     return undef;
1013 }
1014
1015 # Returns the closest copy by proximity that is a confirmed valid
1016 # targetable copy.
1017 sub find_nearest_copy {
1018     my $self = shift;
1019     my %prox_map = %{$self->{weighted_prox_map}};
1020     my $hold = $self->hold;
1021     my %seen;
1022
1023     # Pick a copy at random from each tier of the proximity map,
1024     # starting at the lowest proximity and working up, until a
1025     # copy is found that is suitable for targeting.
1026     for my $prox (sort {$a <=> $b} keys %prox_map) {
1027         my @copies = @{$prox_map{$prox}};
1028         next unless @copies;
1029
1030         my $rand = int(rand(scalar(@copies)));
1031
1032         while (my ($c) = splice(@copies, $rand, 1)) {
1033             $rand = int(rand(scalar(@copies)));
1034             next if $seen{$c->{id}};
1035
1036             return $c if $self->copy_is_permitted($c);
1037             $seen{$c->{id}} = 1;
1038
1039             last unless(@copies);
1040         }
1041     }
1042
1043     return undef;
1044 }
1045
1046 # Returns true if the provided copy passes the hold permit test for our
1047 # hold and can be used for targeting.
1048 # When a copy fails the test, it is removed from $self->copies.
1049 sub copy_is_permitted {
1050     my ($self, $copy) = @_;
1051     return 0 unless $copy;
1052
1053     my $resp = $self->editor->json_query({
1054         from => [
1055             'action.hold_retarget_permit_test',
1056             $self->hold->pickup_lib,
1057             $self->hold->request_lib,
1058             $copy->{id},
1059             $self->hold->usr,
1060             $self->hold->requestor
1061         ]
1062     });
1063
1064     return 1 if $U->is_true($resp->[0]->{success});
1065
1066     # Copy is confirmed non-viable.
1067     # Remove it from our potentials list.
1068     $self->copies([
1069         grep {$_->{id} ne $copy->{id}} @{$self->copies}
1070     ]);
1071
1072     return 0;
1073 }
1074
1075 # Sets hold.current_copy to the provided copy.
1076 sub apply_copy_target {
1077     my ($self, $copy) = @_;
1078     my $e = $self->editor;
1079     my $hold = $self->hold;
1080
1081     $hold->current_copy($copy->{id});
1082     $hold->prev_check_time('now');
1083
1084     $e->update_action_hold_request($hold)
1085         or return $self->exit_targeter("Error updating hold request", 1);
1086
1087     $e->commit;
1088     $self->{success} = 1;
1089     return $self->exit_targeter("successfully targeted copy ".$copy->{id});
1090 }
1091
1092 # Creates a new row in action.unfulfilled_hold_list for our hold.
1093 # Returns 1 if all is OK, false on error.
1094 sub log_unfulfilled_hold {
1095     my $self = shift;
1096     return 1 unless my $prev_id = $self->{previous_copy_id};
1097     my $e = $self->editor;
1098
1099     $self->log_hold(
1100         "hold was not fulfilled by previous targeted copy $prev_id");
1101
1102     my $circ_lib;
1103     if ($self->{valid_previous_copy}) {
1104         $circ_lib = $self->{valid_previous_copy}->{circ_lib};
1105
1106     } else {
1107         # We don't have a handle on the previous copy to get its
1108         # circ lib.  Fetch it.
1109         $circ_lib = $e->retrieve_asset_copy($prev_id)->circ_lib;
1110     }
1111
1112     my $unful = Fieldmapper::action::unfulfilled_hold_list->new;
1113     $unful->hold($self->hold_id);
1114     $unful->circ_lib($circ_lib);
1115     $unful->current_copy($prev_id);
1116
1117     $e->create_action_unfulfilled_hold_list($unful) or
1118         return $self->exit_targeter("Error creating unfulfilled_hold_list", 1);
1119
1120     return 1;
1121 }
1122
1123 sub process_recalls {
1124     my $self = shift;
1125     my $e = $self->editor;
1126
1127     my $pu_lib = $self->hold->pickup_lib;
1128
1129     my $threshold =
1130         $self->parent->get_ou_setting(
1131             $pu_lib, 'circ.holds.recall_threshold', $self->editor)
1132         or return 1;
1133
1134     my $interval =
1135         $self->parent->get_ou_setting(
1136             $pu_lib, 'circ.holds.recall_return_interval', $self->editor)
1137         or return 1;
1138
1139     # Give me the ID of every checked out copy living at the hold
1140     # pickup library.
1141     my @copy_ids = map {$_->{id}}
1142         grep {$_->{circ_lib} eq $pu_lib} @{$self->recall_copies};
1143
1144     return 1 unless @copy_ids;
1145
1146     my $circ = $e->search_action_circulation([
1147         {   target_copy => \@copy_ids,
1148             checkin_time => undef,
1149             duration => {'>' => $threshold}
1150         }, {
1151             order_by => 'due_date',
1152             limit => 1
1153         }
1154     ])->[0];
1155
1156     return unless $circ;
1157
1158     $self->log_hold("recalling circ ".$circ->id);
1159
1160     # Give the user a new due date of either a full recall threshold,
1161     # or the return interval, whichever is further in the future.
1162     my $threshold_date = DateTime::Format::ISO8601
1163         ->parse_datetime(cleanse_ISO8601($circ->xact_start))
1164         ->add(seconds => interval_to_seconds($threshold))
1165         ->iso8601();
1166
1167     my $return_date = DateTime->now(time_zone => 'local')->add(
1168         seconds => interval_to_seconds($interval))->iso8601();
1169
1170     if (DateTime->compare(
1171         DateTime::Format::ISO8601->parse_datetime($threshold_date),
1172         DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1173         $return_date = $threshold_date;
1174     }
1175
1176     my %update_fields = (
1177         due_date => $return_date,
1178         renewal_remaining => 0,
1179     );
1180
1181     my $fine_rules =
1182         $self->parent->get_ou_setting(
1183             $pu_lib, 'circ.holds.recall_fine_rules', $self->editor);
1184
1185     # If the OU hasn't defined new fine rules for recalls, keep them
1186     # as they were
1187     if ($fine_rules) {
1188         $self->log_hold("applying recall fine rules: $fine_rules");
1189         my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1190         $update_fields{recurring_fine} = $rules->[0];
1191         $update_fields{fine_interval} = $rules->[1];
1192         $update_fields{max_fine} = $rules->[2];
1193     }
1194
1195     # Copy updated fields into circ object.
1196     $circ->$_($update_fields{$_}) for keys %update_fields;
1197
1198     $e->update_action_circulation($circ)
1199         or return $self->exit_targeter(
1200             "Error updating circulation object in process_recalls", 1);
1201
1202     # Create trigger event for notifying current user
1203     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1204     $ses->request('open-ils.trigger.event.autocreate',
1205         'circ.recall.target', $circ, $circ->circ_lib);
1206
1207     return 1;
1208 }
1209
1210 # Target a single hold request
1211 sub target {
1212     my ($self, $hold_id) = @_;
1213
1214     my $e = $self->editor;
1215     $self->hold_id($hold_id);
1216
1217     $self->log_hold("processing...");
1218
1219     $e->xact_begin;
1220
1221     my $hold = $e->retrieve_action_hold_request($hold_id)
1222         or return $self->exit_targeter("No hold found", 1);
1223
1224     return $self->exit_targeter("Hold is not eligible for targeting")
1225         if $hold->capture_time     ||
1226            $hold->cancel_time      ||
1227            $hold->fulfillment_time ||
1228            $U->is_true($hold->frozen);
1229
1230     $self->hold($hold);
1231
1232     return unless $self->handle_expired_hold;
1233     return unless $self->get_hold_copies;
1234     return unless $self->update_copy_maps;
1235
1236     # Confirm that we have something to work on.  If we have no
1237     # copies at this point, there's also nothing to recall.
1238     return unless $self->handle_no_copies;
1239
1240     # Trim the set of working copies down to those that are
1241     # currently targetable.
1242     return unless $self->filter_copies_by_status;
1243     return unless $self->filter_copies_in_use;
1244     return unless $self->filter_closed_date_copies;
1245
1246     # Set aside the previously targeted copy for later use as needed.
1247     # Code may exit here in skip_viable mode if the existing
1248     # current_copy value is still viable.
1249     return unless $self->inspect_previous_target;
1250
1251     # Log that the hold was not captured.
1252     return unless $self->log_unfulfilled_hold;
1253
1254     # Confirm again we have something to work on.  If we have no
1255     # targetable copies now, there may be a copy that can be recalled.
1256     return unless $self->handle_no_copies(process_recalls => 1);
1257
1258     # At this point, the working list of copies has been trimmed to
1259     # those that are currently targetable at a superficial level.  
1260     # (They are holdable and available).  Now the code steps through 
1261     # these copies in order of priority and pickup lib proximity to 
1262     # find a copy that is confirmed targetable by policy.
1263
1264     my $copy = $self->attempt_force_recall_target ||
1265                $self->attempt_to_find_copy        ||
1266                $self->attempt_prev_copy_retarget;
1267
1268     # See if one of the above attempt* calls canceled the hold as a side
1269     # effect of looking for a copy to target.
1270     return if $hold->cancel_time;
1271
1272     return $self->apply_copy_target($copy) if $copy;
1273
1274     # No targetable copy was found.  Fire the no-copy handler.
1275     $self->handle_no_copies(force => 1, process_recalls => 1);
1276 }
1277
1278
1279