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