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