1 package OpenILS::Application::Storage::Publisher::action;
2 use parent qw/OpenILS::Application::Storage::Publisher/;
5 use OpenSRF::Utils::Logger qw/:level :logger/;
6 use OpenSRF::Utils qw/:datetime/;
7 use OpenSRF::Utils::JSON;
8 use OpenSRF::AppSession;
9 use OpenSRF::EX qw/:try/;
10 use OpenILS::Utils::Fieldmapper;
11 use OpenILS::Utils::PermitHold;
12 use OpenILS::Utils::CStoreEditor qw/:funcs/;
14 use DateTime::Format::ISO8601;
15 use OpenILS::Utils::Penalty;
17 use OpenILS::Application::Circ::CircCommon;
18 use OpenILS::Application::AppUtils;
19 my $U = "OpenILS::Application::AppUtils";
21 # Used in build_hold_sort_clause(). See the hash %order_by_sprintf_args in
22 # that sub to confirm what gets used to replace the formatters, and see
23 # nearest_hold() for the main body of the SQL query that these go into.
24 my %HOLD_SORT_ORDER_BY = (
26 hprox => 'actor.org_unit_proximity(%d, h.pickup_lib)', # $cp->call_number->owning_lib
27 aprox => 'COALESCE(hm.proximity, p.prox)',
28 approx => 'action.hold_copy_calculated_proximity(h.id, %d, %d)', # $cp,$here
29 priority => 'pgt.hold_priority',
30 cut => 'CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END',
31 depth => 'h.selection_depth',
32 rtime => 'h.request_time',
35 last_event_on_copy.place <> %d AND
36 copy_has_not_been_home.result
37 THEN actor.org_unit_proximity(%d, h.pickup_lib)
40 !, # $cp->call_number->owning_lib x 2
43 last_event_on_copy.place <> %d AND
44 copy_has_not_been_home_even_to_idle.result
45 THEN actor.org_unit_proximity(%d, h.pickup_lib)
48 !, # $cp->call_number->owning_lib x 2
54 return 1 if ($v == 1);
55 return 1 if ($v =~ /^t/io);
56 return 1 if ($v =~ /^y/io);
60 sub ou_ancestor_setting_value_or_cache {
61 # cache should be specific to setting
62 my ($e, $org_id, $setting, $cache) = @_;
64 if (not exists $cache->{$org_id}) {
65 my $r = $U->ou_ancestor_setting(
66 $org_id, $setting, $e # undef $e is ok
70 $cache->{$org_id} = $r->{value};
72 $cache->{$org_id} = undef;
75 return $cache->{$org_id};
78 my $parser = DateTime::Format::ISO8601->new;
79 my $log = 'OpenSRF::Utils::Logger';
81 sub open_noncat_circs {
86 my $a = action::non_cataloged_circulation->table;
87 my $c = config::non_cataloged_type->table;
92 JOIN $c c ON (a.item_type = c.id)
93 WHERE a.circ_time + c.circ_duration > current_timestamp
97 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
99 __PACKAGE__->register_method(
100 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
101 method => 'open_noncat_circs',
107 sub ou_hold_requests {
112 my $h_table = action::hold_request->table;
113 my $c_table = asset::copy->table;
114 my $o_table = actor::org_unit->table;
119 JOIN $c_table cp ON (cp.id = h.current_copy)
120 JOIN $o_table ou ON (ou.id = cp.circ_lib)
122 AND h.capture_time IS NULL
123 AND h.cancel_time IS NULL
124 AND (h.expire_time IS NULL OR h.expire_time > NOW())
125 ORDER BY h.request_time
128 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
131 $client->respond($_) for (
134 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
138 } @{ $sth->fetchall_arrayref }
142 __PACKAGE__->register_method(
143 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
147 method => 'ou_hold_requests',
151 # partition -- if set, an 'undef' will be inserted into the result list
152 # between the last circulation and the first reservation. This is
153 # useful in conjunction with 'idlist' so the caller can tell what type
154 # of transaction the ID refers to without having to query the DB.
155 # skip_no_fines - filter out transactions which will never be billed,
156 # e.g. circs with a $0 max fine or $0 recurring fine.
158 my $upper_interval = shift || '1 millennium';
160 my $partition = shift;
161 my $skip_no_fines = shift;
163 # Only retrieve ID's in the initial query if that's all the caller needs.
164 my $contents = $idlist ? 'id' : '*';
166 my $fines_filter = $skip_no_fines ?
167 'AND recurring_fine <> 0 AND max_fine <> 0' : '';
169 my $c_t = action::circulation->table;
174 WHERE stop_fines IS NULL
176 AND due_date < ( CURRENT_TIMESTAMP - grace_period )
177 AND fine_interval < ?::INTERVAL
180 my $sth = action::circulation->db_Main->prepare_cached($sql);
181 $sth->execute($upper_interval);
183 my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
185 push (@circs, undef) if $partition;
187 $fines_filter = $skip_no_fines ?
188 'AND fine_amount <> 0 AND max_fine <> 0' : '';
190 $c_t = booking::reservation->table;
194 WHERE return_time IS NULL
196 AND end_time < ( CURRENT_TIMESTAMP )
197 AND fine_interval IS NOT NULL
198 AND cancel_time IS NULL
201 $sth = action::circulation->db_Main->prepare_cached($sql);
204 push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
209 sub complete_reshelving {
214 local $OpenILS::Application::Storage::WRITE = 1;
216 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
217 unless (interval_to_seconds( $window ));
219 my $cp = asset::copy->table;
228 AND cp.status_changed_time < NOW() - CAST( COALESCE( BTRIM( (SELECT value FROM actor.org_unit_ancestor_setting('circ.reshelving_complete.interval', cp.circ_lib)),'"' ), ? ) AS INTERVAL)
231 my $sth = action::circulation->db_Main->prepare_cached($sql);
232 $sth->execute($window);
237 __PACKAGE__->register_method(
238 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
241 method => 'complete_reshelving',
244 sub mark_longoverdue {
249 local $OpenILS::Application::Storage::WRITE = 1;
251 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
252 unless (interval_to_seconds( $window ));
254 my $setting = actor::org_unit_setting->table;
255 my $circ = action::circulation->table;
259 SET stop_fines = 'LONGOVERDUE',
260 stop_fines_time = now()
264 LEFT JOIN $setting setting
265 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
266 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
267 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
271 my $sth = action::circulation->db_Main->prepare_cached($sql);
272 $sth->execute($window);
277 __PACKAGE__->register_method(
278 api_name => 'open-ils.storage.action.circulation.long_overdue',
281 method => 'mark_longoverdue',
284 sub auto_thaw_frozen_holds {
288 local $OpenILS::Application::Storage::WRITE = 1;
290 my $holds = action::hold_request->table;
292 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
294 my $sth = action::hold_request->db_Main->prepare_cached($sql);
300 __PACKAGE__->register_method(
301 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
305 method => 'auto_thaw_frozen_holds',
312 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
314 $client->respond( $idlist ? $_ : $_->to_fieldmapper )
315 for ( overdue_circs('', $idlist, undef, 1) );
320 __PACKAGE__->register_method(
321 api_name => 'open-ils.storage.action.circulation.overdue',
324 method => 'grab_overdue',
326 Return list of overdue circulations and reservations to be used for fine generation.
327 Despite the name, this is not a generic method for retrieving all overdue loans,
328 as it excludes loans that have already hit the maximum fine limit
329 and transactions which do not accrue fines.
332 __PACKAGE__->register_method(
333 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
336 method => 'grab_overdue',
339 sub get_hold_sort_order {
342 my $dbh = action::hold_request->db_Main;
344 # The purpose of this function is to return column names in a DB-configured
345 # order, so it won't do to add columns here or change column names unless
346 # you also change the expectation of anything calling this function.
348 my $row = $dbh->selectrow_hashref(
351 cbho.pprox, cbho.hprox, cbho.aprox, cbho.approx, cbho.priority,
352 cbho.cut, cbho.depth, cbho.htime, cbho.shtime, cbho.rtime
353 FROM config.best_hold_order cbho
355 SELECT oils_json_to_text(value)::INT
356 FROM actor.org_unit_ancestor_setting('circ.hold_capture_order', ?)
360 pprox => 1, hprox => 8, aprox => 2, priority => 3,
361 cut => 4, depth => 5, htime => 7, rtime => 6
364 # Return only the keys of our hash, sorted by value,
365 # keys for null values omitted.
367 grep { defined $row->{$_} } (
368 sort {$row->{$a} cmp $row->{$b}} keys %$row
373 # Returns an ORDER BY clause
374 # *and* a string with a CTE expression to precede the nearest-hold SQL query
375 # *and* a string with extra JOIN statements needed
376 sub build_hold_sort_clause {
377 my ($columns, $cp, $here) = @_;
379 my %order_by_sprintf_args = (
380 hprox => [$cp->call_number->owning_lib],
381 approx => [$cp->id, $here],
382 htime => [$cp->call_number->owning_lib, $cp->call_number->owning_lib],
383 shtime => [$cp->call_number->owning_lib, $cp->call_number->owning_lib]
388 foreach my $col (@$columns) {
389 if ($col eq 'htime' and not $ctes_needed) {
391 } elsif ($col eq 'shtime') {
396 @args = @{$order_by_sprintf_args{$col}} if
397 exists $order_by_sprintf_args{$col};
399 push @clauses, sprintf($HOLD_SORT_ORDER_BY{$col}, @args);
401 last if $col eq 'rtime'; # rtime is effectively unique, no need for
402 # more order-by clauses after that.
405 my ($ctes, $joins) = ("", "");
406 if ($ctes_needed >= 1) {
407 # Each CTE serves the next. The first is one version or another
408 # of last_event_on_copy, which is described in holds-go-home.txt
409 # TechRef, but it essentially returns place and time of the most
410 # recent transit or circ to do with a copy, and failing that it
411 # returns a synthetic event that means "here" and "now".
413 if ($ctes_needed == 2) {
415 , last_event_on_copy AS ( -- combined circ and transit version
421 COALESCE(dest_recv_time, source_send_time) AS moment
422 FROM action.transit_copy
423 WHERE target_copy = %d
424 ORDER BY moment DESC LIMIT 1
428 COALESCE(checkin_lib, circ_lib) AS place,
429 COALESCE(checkin_time, xact_start) AS moment
430 FROM action.circulation
431 WHERE target_copy = %d
432 ORDER BY moment DESC LIMIT 1
438 ) x ORDER BY concrete DESC, moment DESC LIMIT 1
439 ) !, $cp->id, $cp->id, $cp->call_number->owning_lib);
442 , last_event_on_copy AS ( -- circ only version
446 COALESCE(checkin_lib, circ_lib) AS place,
447 COALESCE(checkin_time, xact_start) AS moment
448 FROM action.circulation
449 WHERE target_copy = %d
450 ORDER BY moment DESC LIMIT 1
455 ) x ORDER BY concrete DESC, moment DESC LIMIT 1
456 ) !, $cp->id, $cp->call_number->owning_lib);
460 JOIN last_event_on_copy ON (true)
463 # For our next auxiliary query, the question we seek to answer is,
464 # "has our copy been circulating away from home too long?"
466 # Have there been no checkouts at the copy's circ_lib since the
467 # beginning of our go-home interval?
469 # [We use sprintf because the outer function that's going to send one
470 # big query through DBI is blind to our process of dynamically building
471 # these CTEs, and it wouldn't know what bind parameters to pass unless
472 # we did a lot more work here. This is injection-safe because we only
473 # use the %d formatter.]
475 , copy_has_not_been_home AS (
478 SELECT MIN(circ.id) FROM action.circulation circ
479 JOIN go_home_interval ON (true)
481 circ.target_copy = %d AND
482 circ.circ_lib = %d AND
483 circ.xact_start >= NOW() - go_home_interval.value
485 ) !, $cp->id, $cp->circ_lib);
488 JOIN copy_has_not_been_home ON (true)
492 if ($ctes_needed == 2) {
493 # By this query, we mean to determine that the copy hasn't landed at
494 # home by means of transit during the go-home interval (in addition
495 # to not having circulated from home in the same time frame).
497 # There have been no homebound transits that arrived for this copy
498 # since the beginning of the go-home interval.
501 , copy_has_not_been_home_even_to_idle AS (
502 SELECT result AND NOT (
503 SELECT COUNT(*)::INT::BOOL
504 FROM action.transit_copy atc
506 atc.target_copy = %d AND
507 (atc.dest = %d OR atc.source = %d) AND
508 atc.dest_recv_time >= NOW() - (SELECT value FROM go_home_interval)
509 ) AS result FROM copy_has_not_been_home
510 ) !, $cp->id, $cp->circ_lib, $cp->circ_lib);
511 $joins .= " JOIN copy_has_not_been_home_even_to_idle ON (true) ";
515 join(", ", @clauses),
524 my $here = shift; # just the ID
525 my $cp = shift; # now an object with call_number fleshed,
526 # formerly just copy ID
527 my $limit = int(shift()) || 10;
528 my $age = shift() || '0 seconds';
531 $log->info("deprecated 'fifo' param true, but ignored") if isTrue($fifo);
533 # ScriptBuilder fleshes the circ_lib, which confuses things; ensure we
534 # are working with a circ lib ID and not an object
536 if (ref $cp->circ_lib) {
537 $cp_circ_lib = $cp->circ_lib->id;
539 $cp_circ_lib = $cp->circ_lib;
543 if (ref $cp->call_number->owning_lib) {
544 $cp_owning_lib = $cp->call_number->owning_lib->id;
546 $cp_owning_lib = $cp->call_number->owning_lib;
549 my ($holdsort, $addl_cte, $addl_join) =
550 build_hold_sort_clause(get_hold_sort_order($cp_owning_lib), $cp, $here);
552 local $OpenILS::Application::Storage::WRITE = 1;
554 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $cp_circ_lib, $here, $cp->id, $age);
555 WITH go_home_interval AS (
556 SELECT OILS_JSON_TO_TEXT(
557 (SELECT value FROM actor.org_unit_ancestor_setting(
558 'circ.hold_go_home_interval', ?
560 ))::INTERVAL AS value
564 FROM action.hold_request h
565 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
566 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
567 JOIN actor.usr au ON (au.id = h.usr)
568 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
569 LEFT JOIN actor.usr_standing_penalty ausp
570 ON ( au.id = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
571 LEFT JOIN config.standing_penalty csp
572 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
574 WHERE hm.target_copy = ?
575 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR hm.proximity = 0 OR p.prox = 0)
576 AND h.capture_time IS NULL
577 AND h.cancel_time IS NULL
578 AND (h.expire_time IS NULL OR h.expire_time > NOW())
579 AND h.frozen IS FALSE
581 ORDER BY CASE WHEN h.hold_type IN ('R','F') THEN 0 ELSE 1 END, $holdsort
585 $client->respond( $_ ) for ( @$ids );
588 __PACKAGE__->register_method(
589 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
592 method => 'nearest_hold',
595 sub targetable_holds {
598 my $check_expire = shift;
600 $check_expire ||= '12h';
602 local $OpenILS::Application::Storage::WRITE = 1;
604 # json_query can *almost* represent this query, but can't
605 # handle the CASE statement or the interval arithmetic
606 my $query = <<" SQL";
607 SELECT ahr.id, mmsm.metarecord
608 FROM action.hold_request ahr
609 JOIN reporter.hold_request_record USING (id)
610 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
611 WHERE capture_time IS NULL
612 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
613 AND fulfillment_time IS NULL
614 AND cancel_time IS NULL
616 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
618 my $sth = action::hold_request->db_Main->prepare_cached($query);
619 $sth->execute($check_expire);
620 $client->respond( $_ ) for @{ $sth->fetchall_arrayref };
625 __PACKAGE__->register_method(
626 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
629 method => 'targetable_holds',
631 Returns ordered list of hold request and metarecord IDs
632 for all hold requests that are available for initial targeting
634 @param check interval
635 @return list of pairs of hold request and metarecord IDs
639 sub next_resp_group_id {
643 # XXX This is not replication safe!!!
645 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
646 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
650 __PACKAGE__->register_method(
651 api_name => 'open-ils.storage.action.survey_response.next_group_id',
653 method => 'next_resp_group_id',
656 sub patron_circ_summary {
661 return undef unless ($id);
662 my $c_table = action::circulation->table;
663 my $b_table = money::billing->table;
665 $log->debug("Retrieving patron summary for id $id", DEBUG);
667 my $select = <<" SQL";
668 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
670 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
672 AND c.xact_finish IS NULL
674 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
675 OR c.stop_fines IS NULL
679 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
681 __PACKAGE__->register_method(
682 api_name => 'open-ils.storage.action.circulation.patron_summary',
684 method => 'patron_circ_summary',
687 #XXX Fix stored proc calls
688 sub find_local_surveys {
693 return undef unless ($ou);
694 my $s_table = action::survey->table;
696 my $select = <<" SQL";
699 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
700 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
703 my $sth = action::survey->db_Main->prepare_cached($select);
706 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
710 __PACKAGE__->register_method(
711 api_name => 'open-ils.storage.action.survey.all',
714 method => 'find_local_surveys',
717 #XXX Fix stored proc calls
718 sub find_opac_surveys {
723 return undef unless ($ou);
724 my $s_table = action::survey->table;
726 my $select = <<" SQL";
729 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
730 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
734 my $sth = action::survey->db_Main->prepare_cached($select);
737 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
741 __PACKAGE__->register_method(
742 api_name => 'open-ils.storage.action.survey.opac',
745 method => 'find_opac_surveys',
752 my $limit = shift || 10;
753 my $offset = shift || 0;
755 return undef unless ($ou);
756 my $h_table = action::hold_request->table;
757 my $a_table = asset::copy->table;
758 my $ord_table = asset::copy_location_order->table;
760 my $idlist = 1 if ($self->api_name =~/id_list/o);
761 my $count = 1 if ($self->api_name =~/count$/o);
763 my $status_filter = '';
764 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
766 my $select = <<" SQL";
769 JOIN $a_table a ON (h.current_copy = a.id)
770 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
772 AND h.capture_time IS NULL
773 AND h.cancel_time IS NULL
774 AND (h.expire_time IS NULL OR h.expire_time > NOW())
777 FROM actor.usr_standing_penalty ausp
778 JOIN config.standing_penalty csp ON (
779 csp.id = ausp.standing_penalty
780 AND csp.block_list LIKE '%CAPTURE%'
782 WHERE h.usr = ausp.usr
783 AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() )
786 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
793 SELECT count(DISTINCT h.id)
795 JOIN $a_table a ON (h.current_copy = a.id)
797 AND h.capture_time IS NULL
798 AND h.cancel_time IS NULL
799 AND (h.expire_time IS NULL OR h.expire_time > NOW())
802 FROM actor.usr_standing_penalty ausp
803 JOIN config.standing_penalty csp ON (
804 csp.id = ausp.standing_penalty
805 AND csp.block_list LIKE '%CAPTURE%'
807 WHERE h.usr = ausp.usr
808 AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() )
814 my $sth = action::survey->db_Main->prepare_cached($select);
818 $client->respond( $sth->fetchall_arrayref()->[0][0] );
820 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
822 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
827 __PACKAGE__->register_method(
828 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
832 "Returns a count of holds for a specific library's pull list.",
833 [ [org_unit => "The library's org id", "number"] ],
834 ['A count of holds for the stated library to pull ', 'number']
836 method => 'hold_pull_list',
838 __PACKAGE__->register_method(
839 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
843 "Returns a status filtered count of holds for a specific library's pull list.",
844 [ [org_unit => "The library's org id", "number"] ],
845 ['A status filtered count of holds for the stated library to pull ', 'number']
847 method => 'hold_pull_list',
849 __PACKAGE__->register_method(
850 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
854 "Returns the hold ids for a specific library's pull list.",
855 [ [org_unit => "The library's org id", "number"],
856 [limit => 'An optional page size, defaults to 10', 'number'],
857 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
859 ['A list of holds for the stated library to pull for', 'array']
861 method => 'hold_pull_list',
863 __PACKAGE__->register_method(
864 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
868 "Returns the holds for a specific library's pull list.",
869 [ [org_unit => "The library's org id", "number"],
870 [limit => 'An optional page size, defaults to 10', 'number'],
871 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
873 ['A list of holds for the stated library to pull for', 'array']
875 method => 'hold_pull_list',
877 __PACKAGE__->register_method(
878 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
882 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
883 [ [org_unit => "The library's org id", "number"],
884 [limit => 'An optional page size, defaults to 10', 'number'],
885 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
887 ['A list of holds for the stated library to pull for', 'array']
889 method => 'hold_pull_list',
891 __PACKAGE__->register_method(
892 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
896 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
897 [ [org_unit => "The library's org id", "number"],
898 [limit => 'An optional page size, defaults to 10', 'number'],
899 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
901 ['A list of holds for the stated library to pull for', 'array']
903 method => 'hold_pull_list',
906 sub find_optional_surveys {
911 return undef unless ($ou);
912 my $s_table = action::survey->table;
914 my $select = <<" SQL";
917 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
918 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
919 AND s.required IS FALSE;
922 my $sth = action::survey->db_Main->prepare_cached($select);
925 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
929 __PACKAGE__->register_method(
930 api_name => 'open-ils.storage.action.survey.optional',
933 method => 'find_optional_surveys',
936 sub find_required_surveys {
941 return undef unless ($ou);
942 my $s_table = action::survey->table;
944 my $select = <<" SQL";
947 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
948 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
949 AND s.required IS TRUE;
952 my $sth = action::survey->db_Main->prepare_cached($select);
955 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
959 __PACKAGE__->register_method(
960 api_name => 'open-ils.storage.action.survey.required',
963 method => 'find_required_surveys',
966 sub find_usr_summary_surveys {
971 return undef unless ($ou);
972 my $s_table = action::survey->table;
974 my $select = <<" SQL";
977 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
978 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
979 AND s.usr_summary IS TRUE;
982 my $sth = action::survey->db_Main->prepare_cached($select);
985 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
989 __PACKAGE__->register_method(
990 api_name => 'open-ils.storage.action.survey.usr_summary',
993 method => 'find_usr_summary_surveys',
996 sub seconds_to_interval_hash {
997 my $interval = shift;
998 my $limit = shift || 's';
999 $limit =~ s/^(.)/$1/o;
1003 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
1004 my ($year, $month, $week, $day, $hour, $minute, $second) =
1005 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
1007 if ($y = int($interval / (60 * 60 * 24 * 365))) {
1008 $output{$year} = $y;
1009 $ym = $interval % (60 * 60 * 24 * 365);
1013 return %output if ($limit eq 'y');
1015 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
1016 $output{$month} = $M;
1017 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
1021 return %output if ($limit eq 'M');
1023 if ($w = int($Mm / 604800)) {
1024 $output{$week} = $w;
1029 return %output if ($limit eq 'w');
1031 if ($d = int($wm / 86400)) {
1037 return %output if ($limit eq 'd');
1039 if ($h = int($dm / 3600)) {
1040 $output{$hour} = $h;
1045 return %output if ($limit eq 'h');
1047 if ($m = int($hm / 60)) {
1048 $output{$minute} = $m;
1053 return %output if ($limit eq 'm');
1055 if ($s = int($mm)) {
1056 $output{$second} = $s;
1058 $output{$second} = 0 unless (keys %output);
1064 sub generate_fines {
1068 my $overbill = shift;
1070 local $OpenILS::Application::Storage::WRITE = 1;
1075 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
1076 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
1078 push @circs, overdue_circs(undef, 1, 1, 1);
1081 $logger->info("fine generator processing ".scalar(@circs)." transactions");
1083 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
1085 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
1086 my $handling_resvs = 0;
1087 for my $c (@circs) {
1089 my $ctype = ref($c);
1091 if (!$ctype) { # fetched via idlist
1092 if ($handling_resvs) {
1093 $c = booking::reservation->retrieve($c);
1094 } elsif (not defined $c) {
1095 # an undef value is the indicator that we are moving
1096 # from processing circulations to reservations.
1097 $handling_resvs = 1;
1100 $c = action::circulation->retrieve($c);
1105 $ctype =~ s/^.+::(\w+)$/$1/;
1107 my $due_date_method = 'due_date';
1108 my $target_copy_method = 'target_copy';
1109 my $circ_lib_method = 'circ_lib';
1110 my $recurring_fine_method = 'recurring_fine';
1111 my $is_reservation = 0;
1112 if ($ctype eq 'reservation') {
1113 $is_reservation = 1;
1114 $due_date_method = 'end_time';
1115 $target_copy_method = 'current_resource';
1116 $circ_lib_method = 'pickup_lib';
1117 $recurring_fine_method = 'fine_amount';
1118 next unless ($c->fine_interval);
1120 #TODO: reservation grace periods
1121 my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
1124 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1125 $log->debug("Cleaning up after previous transaction\n");
1126 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1128 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1130 sprintf("Processing %s %d...",
1131 ($is_reservation ? "reservation" : "circ"), $c->id
1136 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
1138 my $due = $due_dt->epoch;
1141 my $fine_interval = $c->fine_interval;
1142 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
1143 $fine_interval = interval_to_seconds( $fine_interval );
1145 if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
1146 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
1147 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
1151 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
1152 my $tz_offset_s = 0;
1153 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
1154 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
1157 $due -= ($due % $fine_interval) + $tz_offset_s;
1158 $now -= ($now % $fine_interval) + $tz_offset_s;
1162 "ARG! Overdue $ctype ".$c->id.
1163 " for item ".$c->$target_copy_method.
1164 " (user ".$c->usr.").\n".
1165 "\tItem was due on or before: ".localtime($due)."\n");
1167 my @fines = money::billing->search_where(
1170 billing_ts => { '>' => $c->$due_date_method } },
1171 { order_by => 'billing_ts DESC'}
1175 my $fine = $fines[$f_idx] if (@fines);
1177 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
1180 my $current_fine_total = 0;
1181 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
1185 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
1186 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
1188 $log->info( "Potential first billing for circ ".$c->id );
1191 $grace_period = OpenILS::Application::Circ::CircCommon->extend_grace_period($c->$circ_lib_method->to_fieldmapper->id,$c->$due_date_method,$grace_period,undef,$hoo{$c->$circ_lib_method});
1194 return if ($last_fine > $now);
1195 # Generate fines for each past interval, including the one we are inside
1196 my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
1198 if ( $last_fine == $due # we have no fines yet
1199 && $grace_period # and we have a grace period
1200 && $now < $due + $grace_period # and some date math says were are within the grace period
1202 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
1203 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
1207 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
1208 return unless ($pending_fine_count);
1210 my $recurring_fine = int($c->$recurring_fine_method * 100);
1211 my $max_fine = int($c->max_fine * 100);
1213 my $skip_closed_check = $U->ou_ancestor_setting_value(
1214 $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.charge_when_closed');
1215 $skip_closed_check = $U->is_true($skip_closed_check);
1217 my $truncate_to_max_fine = $U->ou_ancestor_setting_value(
1218 $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.truncate_to_max_fine');
1219 $truncate_to_max_fine = $U->is_true($truncate_to_max_fine);
1221 my ($latest_billing_ts, $latest_amount) = ('',0);
1222 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
1224 if ($current_fine_total >= $max_fine) {
1225 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
1227 "\tMaximum fine level of ".$c->max_fine.
1228 " reached for this $ctype.\n".
1229 "\tNo more fines will be generated.\n" );
1233 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
1234 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
1235 my $current_bill_count = $bill;
1236 while ( $current_bill_count ) {
1237 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
1238 $current_bill_count--;
1241 my $timestamptz = $billing_ts->strftime('%FT%T%z');
1242 if (!$skip_closed_check) {
1243 my $dow = $billing_ts->day_of_week_0();
1244 my $dow_open = "dow_${dow}_open";
1245 my $dow_close = "dow_${dow}_close";
1247 if (my $h = $hoo{$c->$circ_lib_method}) {
1248 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
1251 my @cl = actor::org_unit::closed_date->search_where(
1252 { close_start => { '<=' => $timestamptz },
1253 close_end => { '>=' => $timestamptz },
1254 org_unit => $c->$circ_lib_method }
1259 # The billing amount for this billing normally ought to be the recurring fine amount.
1260 # However, if the recurring fine amount would cause total fines to exceed the max fine amount,
1261 # we may wish to reduce the amount for this billing (if circ.fines.truncate_to_max_fine is true).
1262 my $this_billing_amount = $recurring_fine;
1263 if ( $truncate_to_max_fine && ($current_fine_total + $this_billing_amount) > $max_fine ) {
1264 $this_billing_amount = ($max_fine - $current_fine_total);
1266 $current_fine_total += $this_billing_amount;
1267 $latest_amount += $this_billing_amount;
1268 $latest_billing_ts = $timestamptz;
1270 money::billing->create(
1271 { xact => ''.$c->id,
1272 note => "System Generated Overdue Fine",
1273 billing_type => "Overdue materials",
1275 amount => sprintf('%0.2f', $this_billing_amount/100),
1276 billing_ts => $timestamptz,
1282 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
1283 if ($latest_billing_ts and $latest_amount);
1285 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1289 # Caluclate penalties inline
1290 OpenILS::Utils::Penalty->calculate_penalties(
1291 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
1295 # Calculate penalties with an aysnc call to the penalty server. This approach
1296 # may lead to duplicate penalties since multiple penalty processes for a
1297 # given user may be running at the same time. Leave this here for reference
1298 # in case we later find that asyc calls are needed in some environments.
1300 'open-ils.penalty.patron_penalty.calculate',
1301 { patronid => ''.$c->usr,
1302 context_org => ''.$c->$circ_lib_method,
1313 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
1314 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
1315 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1316 last if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1320 __PACKAGE__->register_method(
1321 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1324 method => 'generate_fines',
1328 sub MR_records_matching_format {
1334 # include all visible copies, regardless of holdability
1335 my $opac_visible = shift;
1337 # find filters for MR holds
1339 if (defined($filter)) {
1340 ($mr_filter) = @{action::hold_request->db_Main->selectcol_arrayref(
1341 'SELECT metabib.compile_composite_attr(?)',
1347 my $records = [metabib::metarecord->retrieve($MR)->source_records];
1349 my $vis_q = 'asset.record_has_holdable_copy(?,?)';
1350 if ($opac_visible) {
1353 SELECT 1 FROM asset.opac_visible_copies
1354 WHERE record = ? AND circ_lib IN (
1355 SELECT id FROM actor.org_unit_descendants(?)
1361 my $q = "SELECT source FROM metabib.record_attr_vector_list WHERE source = ? AND vlist @@ ? AND $vis_q";
1362 my @args = ( $mr_filter, $org );
1364 $q = "SELECT true WHERE $vis_q";
1368 for my $r ( map { isTrue($_->deleted) ? () : ($_->id) } @$records ) {
1369 # the map{} below is tricky. it puts the record ID in front of each param. see $q above
1370 $client->respond($r)
1371 if @{action::hold_request->db_Main->selectcol_arrayref( $q, {}, map { ( $r => $_ ) } @args )};
1374 return; # discard final l-val
1376 __PACKAGE__->register_method(
1377 api_name => 'open-ils.storage.metarecord.filtered_records',
1381 method => 'MR_records_matching_format',
1385 sub new_hold_copy_targeter {
1388 my $check_expire = shift;
1389 my $one_hold = shift;
1390 my $find_copy = shift;
1392 local $OpenILS::Application::Storage::WRITE = 1;
1394 $self->{target_weight} = {};
1395 $self->{max_loops} = {};
1401 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1402 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
1403 } elsif ( $check_expire ) {
1405 # what's the retarget time threashold?
1407 $check_expire ||= '12h';
1408 $check_expire = interval_to_seconds( $check_expire );
1410 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1413 my $expire_threshold = sprintf(
1414 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1415 $year, $mon, $mday, $hour, $min, $sec
1418 # find all the holds holds needing retargeting
1419 $holds = [ action::hold_request->search_where(
1420 { capture_time => undef,
1421 fulfillment_time => undef,
1422 cancel_time => undef,
1424 prev_check_time => { '<=' => $expire_threshold },
1426 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
1428 # find all the holds holds needing first time targeting
1429 push @$holds, action::hold_request->search(
1430 capture_time => undef,
1431 fulfillment_time => undef,
1432 prev_check_time => undef,
1434 cancel_time => undef,
1435 { order_by => 'selection_depth DESC, request_time' } );
1438 # find all the holds holds needing first time targeting ONLY
1439 $holds = [ action::hold_request->search(
1440 capture_time => undef,
1441 fulfillment_time => undef,
1442 prev_check_time => undef,
1443 cancel_time => undef,
1445 { order_by => 'selection_depth DESC, request_time' } ) ];
1447 } catch Error with {
1449 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1452 my @closed = actor::org_unit::closed_date->search_where(
1453 { close_start => { '<=', 'now' },
1454 close_end => { '>=', 'now' } }
1457 if ($check_expire) {
1459 # $check_expire, if it exists, was already converted to seconds
1460 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1464 my $next_check_time = sprintf(
1465 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1466 $year, $mon, $mday, $hour, $min, $sec
1470 my @closed_at_next = actor::org_unit::closed_date->search_where(
1471 { close_start => { '<=', $next_check_time },
1472 close_end => { '>=', $next_check_time } }
1476 for my $c_at_n (@closed_at_next) {
1477 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1478 push @new_closed, $c_at_n;
1481 @closed = @new_closed;
1485 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1486 my $editor = new_editor;
1488 my $target_when_closed = {};
1489 my $target_when_closed_if_at_pickup_lib = {};
1491 for my $hold (@$holds) {
1493 #start a transaction if needed
1494 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1495 $log->debug("Cleaning up after previous transaction\n");
1496 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1498 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1499 $log->info("Processing hold ".$hold->id."...\n");
1501 #first, re-fetch the hold, to make sure it's not captured already
1502 $hold->remove_from_object_index();
1503 $hold = action::hold_request->retrieve( $hold->id );
1505 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1507 # remove old auto-targeting maps
1508 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1509 $_->delete for (@oldmaps);
1511 if ($hold->expire_time) {
1512 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1513 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1515 # cancel cause = un-targeted expiration
1516 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1518 # refresh fields from the DB while still in the xact
1519 my $fm_hold = $hold->to_fieldmapper;
1521 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1523 # tell A/T the hold was cancelled
1524 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1525 $ses->request('open-ils.trigger.event.autocreate',
1526 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1532 my $all_copies = [];
1534 # find all the potential copies
1535 if ($hold->hold_type eq 'M') {
1537 $self->method_lookup(
1538 'open-ils.storage.metarecord.filtered_records'
1539 )->run( $hold->target, $hold->holdable_formats )
1542 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1543 ->run( $r_id, $hold->selection_ou, $hold->selection_depth );
1545 for my $cn ( @{ $rtree->call_numbers } ) {
1547 asset::copy->search_where(
1548 { id => [map {$_->id} @{ $cn->copies }],
1550 ) if ($cn && @{ $cn->copies });
1553 } elsif ($hold->hold_type eq 'T') {
1555 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1556 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1559 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1563 for my $cn ( @{ $rtree->call_numbers } ) {
1565 asset::copy->search_where(
1566 { id => [map {$_->id} @{ $cn->copies }],
1568 ) if ($cn && @{ $cn->copies });
1570 } elsif ($hold->hold_type eq 'V') {
1572 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1573 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1576 asset::copy->search_where(
1577 { id => [map {$_->id} @{ $vtree->copies }],
1579 ) if ($vtree && @{ $vtree->copies });
1581 } elsif ($hold->hold_type eq 'P') {
1582 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1584 asset::copy->search_where(
1585 { id => [map {$_->target_copy} @part_maps],
1590 } elsif ($hold->hold_type eq 'I') {
1592 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1593 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1596 asset::copy->search_where(
1597 { id => [map {$_->unit->id} @{ $itree->items }],
1599 ) if ($itree && @{ $itree->items });
1601 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1602 my $_cp = asset::copy->retrieve($hold->target);
1603 push @$all_copies, $_cp if $_cp;
1606 # Force and recall holds bypass pretty much everything
1607 if ($hold->hold_type ne 'R' && $hold->hold_type ne 'F') {
1609 @$all_copies = grep { isTrue($_->status->holdable) &&
1610 isTrue($_->location->holdable) &&
1611 isTrue($_->holdable) &&
1612 !isTrue($_->deleted) &&
1613 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1614 ( ( $hold->hold_type ne 'C' && $hold->hold_type ne 'I' # Copy-level holds don't care about parts
1615 && $hold->hold_type ne 'P' ) ? $_->part_maps->count == 0 : 1)
1619 # let 'em know we're still working
1620 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1622 # if we have no copies ...
1623 if (!ref $all_copies || !@$all_copies) {
1624 $log->info("\tNo copies available for targeting at all!\n");
1625 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1627 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1628 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1632 my $copy_count = @$all_copies;
1633 my $found_copy = undef;
1634 $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1636 # map the potentials, so that we can pick up checkins
1637 my $hold_copy_map = {};
1638 $hold_copy_map->{$_->hold}->{$_->target_copy} = $_->proximity
1641 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } )
1645 my $pu_lib = ''.$hold->pickup_lib;
1646 my $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
1647 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1649 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1652 for my $c (@$all_copies) {
1654 next if ($hold->current_copy and $c->id eq $hold->current_copy);
1656 # skip on circ lib is closed IFF we care
1659 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1660 $ignore_closing = ou_ancestor_setting_value_or_cache(
1663 'circ.holds.target_when_closed_if_at_pickup_lib',
1664 $target_when_closed_if_at_pickup_lib
1667 if (not $ignore_closing) { # one more chance to find a reason
1668 # to ignore OU closedness.
1669 $ignore_closing = ou_ancestor_setting_value_or_cache(
1672 'circ.holds.target_when_closed',
1678 # "For hold " . $hold->id . " and copy with circ_lib " .
1679 # $c->circ_lib . " we " .
1680 # ($ignore_closing ? "ignore" : "respect")
1685 (not $ignore_closing) and
1686 (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1689 # target of another hold
1690 next if (action::hold_request
1692 { current_copy => $c->id,
1693 fulfillment_time => undef,
1694 cancel_time => undef,
1699 # we passed all three, keep it
1700 push @good_copies, $c if ($c);
1701 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1704 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1706 my $old_best = $hold->current_copy;
1707 my $old_best_still_valid = 0; # Assume no, but the next line says yes if it is still a potential.
1708 $old_best_still_valid = 1 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies );
1709 $hold->update({ current_copy => undef }) if ($old_best);
1711 if (!scalar(@good_copies)) {
1712 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1713 if ( $old_best_still_valid ) {
1714 # the old copy is still available
1715 $log->debug("\tPushing current_copy back onto the targeting list");
1716 push @good_copies, $old_best;
1718 # oops, old copy is not available
1719 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1720 $hold->update( { prev_check_time => 'today' } );
1721 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1722 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1727 # reset prox list after trimming good copies
1728 $prox_list = create_prox_list(
1730 [ grep { $_->status == 0 || $_->status == 7 } @good_copies ],
1731 $hold, $hold_copy_map
1734 $all_copies = [ grep { ''.$_->circ_lib ne $pu_lib && ( $_->status == 0 || $_->status == 7 ) } @good_copies ];
1736 my $min_prox = [ sort keys %$prox_list ]->[0];
1738 if ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') { # Recall/Force holds bypass hold rules.
1739 $best = $good_copies[0] if(scalar @good_copies);
1741 $best = choose_nearest_copy($hold, { $min_prox => delete($$prox_list{$min_prox}) });
1744 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1747 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1749 $self->{max_loops}{$pu_lib} = $U->ou_ancestor_setting(
1750 $pu_lib, 'circ.holds.max_org_unit_target_loops', $editor
1753 if (defined($self->{max_loops}{$pu_lib})) {
1754 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1756 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1757 my $circ_lib_list = [keys %circ_lib_map];
1759 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1761 # Grab the "biggest" loop for this hold so far
1762 my $current_loop = $cstore->request(
1763 'open-ils.cstore.json_query',
1765 select => { aufhmxl => ['max'] },
1767 where => { hold => $hold->id}
1771 $current_loop = $current_loop->{max} if ($current_loop);
1772 $current_loop ||= 1;
1774 my $exclude_list = $cstore->request(
1775 'open-ils.cstore.json_query.atomic',
1777 select => { aufhol => ['circ_lib'] },
1779 where => { hold => $hold->id}
1784 if ($exclude_list && @$exclude_list) {
1785 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1786 # check to see if we've used up every library in the potentials list
1787 for my $l ( @$circ_lib_list ) {
1789 for my $ex ( @$exclude_list ) {
1795 push(@keepers, $l) if ($keep);
1798 @keepers = @$circ_lib_list;
1801 $current_loop++ if (!@keepers);
1803 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1804 # We haven't exceeded max_loops yet
1806 for my $cp ( @$all_copies ) {
1807 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1810 $all_copies = [@keeper_copies];
1812 # We have, and should remove potentials and cancel the hold
1813 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1814 $_->delete for (@oldmaps);
1816 # cancel cause = un-targeted expiration
1817 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1819 # refresh fields from the DB while still in the xact
1820 my $fm_hold = $hold->to_fieldmapper;
1822 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1824 # tell A/T the hold was cancelled
1825 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1826 $ses->request('open-ils.trigger.event.autocreate',
1827 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1832 $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
1834 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1838 $best = choose_nearest_copy($hold, $prox_list);
1841 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1843 # hold wasn't fulfilled, record the fact
1845 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1846 action::unfulfilled_hold_list->create(
1847 { hold => ''.$hold->id,
1848 current_copy => ''.$old_best->id,
1849 circ_lib => ''.$old_best->circ_lib,
1854 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1855 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1857 $old_best_still_valid &&
1858 !action::hold_request
1860 { current_copy => $old_best->id,
1861 fulfillment_time => undef,
1862 cancel_time => undef,
1865 ( OpenILS::Utils::PermitHold::permit_copy_hold(
1866 { title => $old_best->call_number->record->to_fieldmapper,
1867 patron => $hold->usr->to_fieldmapper,
1868 copy => $old_best->to_fieldmapper,
1869 requestor => $hold->requestor->to_fieldmapper,
1870 request_lib => $hold->request_lib->to_fieldmapper,
1871 pickup_lib => $hold->pickup_lib->id,
1876 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1877 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1879 $hold->update( { prev_check_time => 'now' } );
1880 $log->info( "\tThere were no targetable copies for the hold" );
1881 process_recall($actor, $log, $hold, \@good_copies);
1884 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1885 $log->info("\tProcessing of hold ".$hold->id." complete.");
1888 { hold => $hold->id,
1889 old_target => ($old_best ? $old_best->id : undef),
1890 eligible_copies => $copy_count,
1891 target => ($best ? $best->id : undef),
1892 found_copy => $found_copy };
1897 $log->error("Processing of hold failed: $e");
1898 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1899 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1906 __PACKAGE__->register_method(
1907 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1909 method => 'new_hold_copy_targeter',
1912 sub process_recall {
1913 my ($actor, $log, $hold, $good_copies) = @_;
1915 # Bail early if we don't have required settings to avoid spurious requests
1916 my ($recall_threshold, $return_interval, $fine_rules);
1918 my $rv = $actor->request(
1919 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1923 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1926 $recall_threshold = $rv->{value};
1928 $rv = $actor->request(
1929 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1933 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1936 $return_interval = $rv->{value};
1938 $rv = $actor->request(
1939 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1943 $fine_rules = $rv->{value};
1946 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1948 # We want checked out copies (status = 1) at the hold pickup lib
1949 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1951 my @copy_ids = map { $_->id } @$all_copies;
1953 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1955 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1957 # Iterate over the checked-out copies to find a copy with a
1958 # loan period longer than the recall threshold:
1959 my $circs = [ action::circulation->search_where(
1960 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1961 { order_by => 'due_date ASC' }
1964 # If we have a candidate copy, then:
1965 if (scalar(@$circs)) {
1966 my $circ = $circs->[0];
1967 $log->info("Recalling circ ID : " . $circ->id);
1969 # Give the user a new due date of either a full recall threshold,
1970 # or the return interval, whichever is further in the future
1971 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1972 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1973 $return_date = $threshold_date;
1976 my $update_fields = {
1977 due_date => $return_date,
1978 renewal_remaining => 0,
1981 # If the OU hasn't defined new fine rules for recalls, keep them
1984 $log->info("Apply recall fine rules: $fine_rules");
1985 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1986 $update_fields->{recurring_fine} = $rules->[0];
1987 $update_fields->{fine_interval} = $rules->[1];
1988 $update_fields->{max_fine} = $rules->[2];
1991 # Adjust circ for current user
1992 $circ->update($update_fields);
1994 # Create trigger event for notifying current user
1995 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1996 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1999 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
2002 sub reservation_targeter {
2005 my $one_reservation = shift;
2007 local $OpenILS::Application::Storage::WRITE = 1;
2012 if ($one_reservation) {
2013 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
2014 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
2017 # find all the reservations needing targeting
2019 booking::reservation->search_where(
2020 { current_resource => undef,
2021 cancel_time => undef,
2022 start_time => { '>' => 'now' }
2024 { order_by => 'start_time' }
2028 } catch Error with {
2030 die "Could not retrieve reservation requests:\n\n$e\n";
2034 for my $bresv (@$reservations) {
2036 #start a transaction if needed
2037 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
2038 $log->debug("Cleaning up after previous transaction\n");
2039 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
2041 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
2042 $log->info("Processing reservation ".$bresv->id."...\n");
2044 #first, re-fetch the hold, to make sure it's not captured already
2045 $bresv->remove_from_object_index();
2046 $bresv = booking::reservation->retrieve( $bresv->id );
2048 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
2050 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
2051 if (DateTime->compare($end_time, DateTime->now) < 0) {
2053 # cancel cause = un-targeted expiration
2054 $bresv->update( { cancel_time => 'now' } );
2056 # refresh fields from the DB while still in the xact
2057 my $fm_bresv = $bresv->to_fieldmapper;
2059 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2061 # tell A/T the reservation was cancelled
2062 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
2063 $ses->request('open-ils.trigger.event.autocreate',
2064 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
2069 my $possible_resources;
2071 # find all the potential resources
2072 if (!$bresv->target_resource) {
2073 my $filter = { type => $bresv->target_resource_type };
2074 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
2076 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
2078 $filter->{available} = [$bresv->start_time, $bresv->end_time];
2079 my $ses = OpenSRF::AppSession->create('open-ils.booking');
2080 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
2082 $possible_resources = $bresv->target_resource;
2085 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
2086 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
2089 my @good_resources = ();
2091 for my $res (@$all_resources) {
2092 unless (isTrue($res->type->catalog_item)) {
2093 push @good_resources, $res;
2097 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
2100 push @good_resources, $res;
2104 # At this point, if we're just targeting one specific
2105 # resource, just succeed. We don't care about its present
2107 if ($bresv->target_resource) {
2108 push @good_resources, $res;
2112 if ($copy->status->id == 0 || $copy->status->id == 7) {
2113 push @good_resources, $res;
2117 if ($copy->status->id == 1) {
2118 my $circs = [ action::circulation->search_where(
2119 {target_copy => $copy->id, checkin_time => undef },
2120 { order_by => 'id DESC' }
2124 my $due_date = $circs->[0]->due_date;
2125 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
2126 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
2127 if (DateTime->compare($start_time, $due_date) < 0) {
2128 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
2132 push @good_resources, $res;
2138 push @good_resources, $res if (isTrue($copy->status->holdable));
2141 # let 'em know we're still working
2142 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2144 # if we have no copies ...
2145 if (!@good_resources) {
2146 $log->info("\tNo resources available for targeting at all!\n");
2147 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
2150 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2154 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
2156 # LFW: note that after the inclusion of hold proximity
2157 # adjustment, this prox_list is the only prox_list
2158 # array in this perl package. Other occurences are
2164 $_->owner == $bresv->pickup_lib
2168 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
2169 # $all_copies is now a list of copies not at the pickup library
2171 my $best = shift @good_resources;
2172 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2175 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
2179 sort { $a->[0] <=> $b->[0] }
2181 [ actor::org_unit_proximity->search_where(
2182 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
2188 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2190 $best = shift @$prox_list
2194 $bresv->update( { current_resource => ''.$best->id } );
2195 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
2198 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2199 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
2202 { reservation => $bresv->id,
2203 current_resource => ($best ? $best->id : undef) };
2208 $log->error("Processing of bresv failed: $e");
2209 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
2210 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
2217 __PACKAGE__->register_method(
2218 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
2220 method => 'reservation_targeter',
2225 my %cache = (titles => {}, cns => {});
2227 sub copy_hold_capture {
2232 if (!defined($cps)) {
2234 $cps = [ asset::copy->search( id => $hold->target ) ];
2235 } catch Error with {
2237 die "Could not retrieve initial volume list:\n\n$e\n";
2241 my @copies = grep { $_->holdable } @$cps;
2243 for (my $i = 0; $i < @$cps; $i++) {
2244 next unless $$cps[$i];
2246 my $cn = $cache{cns}{$copies[$i]->call_number};
2247 my $rec = $cache{titles}{$cn->record};
2248 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
2249 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
2250 $copies[$i] = undef if (
2252 !$self->{user_filter}->request(
2253 'open-ils.circ.permit_hold',
2254 $hold->to_fieldmapper, do {
2255 my $cp_fm = $copies[$i]->to_fieldmapper;
2256 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
2257 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
2258 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
2261 { title => $rec->to_fieldmapper,
2262 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
2263 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
2266 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
2269 @copies = grep { $_ } @copies;
2271 my $count = @copies;
2273 return unless ($count);
2275 action::hold_copy_map->search( hold => $hold->id )->delete_all;
2278 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
2279 for my $c (@copies) {
2280 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
2282 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
2288 sub choose_nearest_copy {
2290 my $prox_list = shift;
2292 for my $p ( sort keys %$prox_list ) {
2293 next unless (ref $$prox_list{$p});
2295 my @capturable = @{ $$prox_list{$p} };
2296 next unless (@capturable);
2298 my $rand = int(rand(scalar(@capturable)));
2300 while (my ($c) = splice(@capturable, $rand, 1)) {
2301 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
2302 { title => $c->call_number->record->to_fieldmapper,
2303 patron => $hold->usr->to_fieldmapper,
2304 copy => $c->to_fieldmapper,
2305 requestor => $hold->requestor->to_fieldmapper,
2306 request_lib => $hold->request_lib->to_fieldmapper,
2307 pickup_lib => $hold->pickup_lib->id,
2313 last unless(@capturable);
2314 $rand = int(rand(scalar(@capturable)));
2319 sub create_prox_list {
2324 my $hold_copy_map = shift || {};
2327 my $editor = new_editor;
2328 for my $cp (@$copies) {
2329 my $prox = $hold_copy_map->{"$hold"}->{"$cp"}; # Allow CDBI stringification to get the pkey
2330 ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib, $hold ) unless (defined $prox);
2331 next unless (defined($prox));
2333 my $copy_circ_lib = ''.$cp->circ_lib;
2334 # Fetch the weighting value for hold targeting, defaulting to 1
2335 $self->{target_weight}{$copy_circ_lib} ||= $U->ou_ancestor_setting(
2336 $copy_circ_lib.'', 'circ.holds.org_unit_target_weight', $editor
2338 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
2339 $self->{target_weight}{$copy_circ_lib} ||= 1;
2341 $prox_list{$prox} = [] unless defined($prox_list{$prox});
2342 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
2343 push @{$prox_list{$prox}}, $cp;
2349 sub volume_hold_capture {
2354 if (!defined($vols)) {
2356 $vols = [ asset::call_number->search( id => $hold->target ) ];
2357 $cache{cns}{$_->id} = $_ for (@$vols);
2358 } catch Error with {
2360 die "Could not retrieve initial volume list:\n\n$e\n";
2364 my @v_ids = map { $_->id } @$vols;
2368 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
2370 } catch Error with {
2372 warn "Could not retrieve copy list:\n\n$e\n";
2375 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
2378 sub title_hold_capture {
2383 if (!defined($titles)) {
2385 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
2386 $cache{titles}{$_->id} = $_ for (@$titles);
2387 } catch Error with {
2389 die "Could not retrieve initial title list:\n\n$e\n";
2393 my @t_ids = map { $_->id } @$titles;
2396 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
2398 } catch Error with {
2400 warn "Could not retrieve volume list:\n\n$e\n";
2403 $cache{cns}{$_->id} = $_ for (@$cn_list);
2405 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);