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;
16 use OpenILS::Application::Circ::CircCommon;
17 use OpenILS::Application::AppUtils;
18 my $U = "OpenILS::Application::AppUtils";
20 # Used in build_hold_sort_clause(). See the hash %order_by_sprintf_args in
21 # that sub to confirm what gets used to replace the formatters, and see
22 # nearest_hold() for the main body of the SQL query that these go into.
23 my %HOLD_SORT_ORDER_BY = (
25 hprox => 'actor.org_unit_proximity(%d, h.pickup_lib)', # $cp->call_number->owning_lib
26 aprox => 'COALESCE(hm.proximity, p.prox)',
27 approx => 'action.hold_copy_calculated_proximity(h.id, %d, %d)', # $cp,$here
28 priority => 'pgt.hold_priority',
29 cut => 'CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END',
30 depth => 'h.selection_depth',
31 rtime => 'h.request_time',
34 last_event_on_copy.place <> %d AND
35 copy_has_not_been_home.result
36 THEN actor.org_unit_proximity(%d, h.pickup_lib)
39 !, # $cp->call_number->owning_lib x 2
42 last_event_on_copy.place <> %d AND
43 copy_has_not_been_home_even_to_idle.result
44 THEN actor.org_unit_proximity(%d, h.pickup_lib)
47 !, # $cp->call_number->owning_lib x 2
53 return 1 if ($v == 1);
54 return 1 if ($v =~ /^t/io);
55 return 1 if ($v =~ /^y/io);
59 sub ou_ancestor_setting_value_or_cache {
60 # cache should be specific to setting
61 my ($e, $org_id, $setting, $cache) = @_;
63 if (not exists $cache->{$org_id}) {
64 my $r = $U->ou_ancestor_setting(
65 $org_id, $setting, $e # undef $e is ok
69 $cache->{$org_id} = $r->{value};
71 $cache->{$org_id} = undef;
74 return $cache->{$org_id};
77 my $parser = DateTime::Format::ISO8601->new;
78 my $log = 'OpenSRF::Utils::Logger';
80 sub open_noncat_circs {
85 my $a = action::non_cataloged_circulation->table;
86 my $c = config::non_cataloged_type->table;
91 JOIN $c c ON (a.item_type = c.id)
92 WHERE a.circ_time + c.circ_duration > current_timestamp
96 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
98 __PACKAGE__->register_method(
99 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
100 method => 'open_noncat_circs',
106 sub ou_hold_requests {
111 my $h_table = action::hold_request->table;
112 my $c_table = asset::copy->table;
113 my $o_table = actor::org_unit->table;
118 JOIN $c_table cp ON (cp.id = h.current_copy)
119 JOIN $o_table ou ON (ou.id = cp.circ_lib)
121 AND h.capture_time IS NULL
122 AND h.cancel_time IS NULL
123 AND (h.expire_time IS NULL OR h.expire_time > NOW())
124 ORDER BY h.request_time
127 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
130 $client->respond($_) for (
133 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
137 } @{ $sth->fetchall_arrayref }
141 __PACKAGE__->register_method(
142 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
146 method => 'ou_hold_requests',
150 # partition -- if set, an 'undef' will be inserted into the result list
151 # between the last circulation and the first reservation. This is
152 # useful in conjunction with 'idlist' so the caller can tell what type
153 # of transaction the ID refers to without having to query the DB.
154 # skip_no_fines - filter out transactions which will never be billed,
155 # e.g. circs with a $0 max fine or $0 recurring fine.
157 my $upper_interval = shift || '1 millennium';
159 my $partition = shift;
160 my $skip_no_fines = shift;
162 # Only retrieve ID's in the initial query if that's all the caller needs.
163 my $contents = $idlist ? 'id' : '*';
165 my $fines_filter = $skip_no_fines ?
166 'AND recurring_fine <> 0 AND max_fine <> 0' : '';
168 my $c_t = action::circulation->table;
173 WHERE stop_fines IS NULL
175 AND due_date < ( CURRENT_TIMESTAMP - grace_period )
176 AND fine_interval < ?::INTERVAL
179 my $sth = action::circulation->db_Main->prepare_cached($sql);
180 $sth->execute($upper_interval);
182 my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
184 push (@circs, undef) if $partition;
186 $fines_filter = $skip_no_fines ?
187 'AND fine_amount <> 0 AND max_fine <> 0' : '';
189 $c_t = booking::reservation->table;
193 WHERE return_time IS NULL
195 AND end_time < ( CURRENT_TIMESTAMP )
196 AND fine_interval IS NOT NULL
197 AND cancel_time IS NULL
200 $sth = action::circulation->db_Main->prepare_cached($sql);
203 push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
208 sub complete_reshelving {
213 local $OpenILS::Application::Storage::WRITE = 1;
215 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
216 unless (interval_to_seconds( $window ));
218 my $cp = asset::copy->table;
227 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)
230 my $sth = action::circulation->db_Main->prepare_cached($sql);
231 $sth->execute($window);
236 __PACKAGE__->register_method(
237 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
240 method => 'complete_reshelving',
243 sub mark_longoverdue {
248 local $OpenILS::Application::Storage::WRITE = 1;
250 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
251 unless (interval_to_seconds( $window ));
253 my $setting = actor::org_unit_setting->table;
254 my $circ = action::circulation->table;
258 SET stop_fines = 'LONGOVERDUE',
259 stop_fines_time = now()
263 LEFT JOIN $setting setting
264 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
265 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
266 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
270 my $sth = action::circulation->db_Main->prepare_cached($sql);
271 $sth->execute($window);
276 __PACKAGE__->register_method(
277 api_name => 'open-ils.storage.action.circulation.long_overdue',
280 method => 'mark_longoverdue',
283 sub auto_thaw_frozen_holds {
287 local $OpenILS::Application::Storage::WRITE = 1;
289 my $holds = action::hold_request->table;
291 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
293 my $sth = action::hold_request->db_Main->prepare_cached($sql);
299 __PACKAGE__->register_method(
300 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
304 method => 'auto_thaw_frozen_holds',
311 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
313 $client->respond( $idlist ? $_ : $_->to_fieldmapper )
314 for ( overdue_circs('', $idlist, undef, 1) );
319 __PACKAGE__->register_method(
320 api_name => 'open-ils.storage.action.circulation.overdue',
323 method => 'grab_overdue',
325 Return list of overdue circulations and reservations to be used for fine generation.
326 Despite the name, this is not a generic method for retrieving all overdue loans,
327 as it excludes loans that have already hit the maximum fine limit
328 and transactions which do not accrue fines.
331 __PACKAGE__->register_method(
332 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
335 method => 'grab_overdue',
338 sub get_hold_sort_order {
341 my $dbh = action::hold_request->db_Main;
343 # The purpose of this function is to return column names in a DB-configured
344 # order, so it won't do to add columns here or change column names unless
345 # you also change the expectation of anything calling this function.
347 my $row = $dbh->selectrow_hashref(
350 cbho.pprox, cbho.hprox, cbho.aprox, cbho.approx, cbho.priority,
351 cbho.cut, cbho.depth, cbho.htime, cbho.shtime, cbho.rtime
352 FROM config.best_hold_order cbho
354 SELECT oils_json_to_text(value)::INT
355 FROM actor.org_unit_ancestor_setting('circ.hold_capture_order', ?)
359 pprox => 1, hprox => 8, aprox => 2, priority => 3,
360 cut => 4, depth => 5, htime => 7, rtime => 6
363 # Return only the keys of our hash, sorted by value,
364 # keys for null values omitted.
366 grep { defined $row->{$_} } (
367 sort {$row->{$a} cmp $row->{$b}} keys %$row
372 # Returns an ORDER BY clause
373 # *and* a string with a CTE expression to precede the nearest-hold SQL query
374 # *and* a string with extra JOIN statements needed
375 sub build_hold_sort_clause {
376 my ($columns, $cp, $here) = @_;
378 my %order_by_sprintf_args = (
379 hprox => [$cp->call_number->owning_lib],
380 approx => [$cp->id, $here],
381 htime => [$cp->call_number->owning_lib, $cp->call_number->owning_lib],
382 shtime => [$cp->call_number->owning_lib, $cp->call_number->owning_lib]
387 foreach my $col (@$columns) {
388 if ($col eq 'htime' and not $ctes_needed) {
390 } elsif ($col eq 'shtime') {
395 @args = @{$order_by_sprintf_args{$col}} if
396 exists $order_by_sprintf_args{$col};
398 push @clauses, sprintf($HOLD_SORT_ORDER_BY{$col}, @args);
400 last if $col eq 'rtime'; # rtime is effectively unique, no need for
401 # more order-by clauses after that.
404 my ($ctes, $joins) = ("", "");
405 if ($ctes_needed >= 1) {
406 # Each CTE serves the next. The first is one version or another
407 # of last_event_on_copy, which is described in holds-go-home.txt
408 # TechRef, but it essentially returns place and time of the most
409 # recent transit or circ to do with a copy, and failing that it
410 # returns a synthetic event that means "here" and "now".
412 if ($ctes_needed == 2) {
414 , last_event_on_copy AS ( -- combined circ and transit version
420 COALESCE(dest_recv_time, source_send_time) AS moment
421 FROM action.transit_copy
422 WHERE target_copy = %d
423 ORDER BY moment DESC LIMIT 1
427 COALESCE(checkin_lib, circ_lib) AS place,
428 COALESCE(checkin_time, xact_start) AS moment
429 FROM action.circulation
430 WHERE target_copy = %d
431 ORDER BY moment DESC LIMIT 1
437 ) x ORDER BY concrete DESC, moment DESC LIMIT 1
438 ) !, $cp->id, $cp->id, $cp->call_number->owning_lib);
441 , last_event_on_copy AS ( -- circ only version
445 COALESCE(checkin_lib, circ_lib) AS place,
446 COALESCE(checkin_time, xact_start) AS moment
447 FROM action.circulation
448 WHERE target_copy = %d
449 ORDER BY moment DESC LIMIT 1
454 ) x ORDER BY concrete DESC, moment DESC LIMIT 1
455 ) !, $cp->id, $cp->call_number->owning_lib);
459 JOIN last_event_on_copy ON (true)
462 # For our next auxiliary query, the question we seek to answer is,
463 # "has our copy been circulating away from home too long?"
465 # Have there been no checkouts at the copy's circ_lib since the
466 # beginning of our go-home interval?
468 # [We use sprintf because the outer function that's going to send one
469 # big query through DBI is blind to our process of dynamically building
470 # these CTEs, and it wouldn't know what bind parameters to pass unless
471 # we did a lot more work here. This is injection-safe because we only
472 # use the %d formatter.]
474 , copy_has_not_been_home AS (
477 SELECT MIN(circ.id) FROM action.circulation circ
478 JOIN go_home_interval ON (true)
480 circ.target_copy = %d AND
481 circ.circ_lib = %d AND
482 circ.xact_start >= NOW() - go_home_interval.value
484 ) !, $cp->id, $cp->circ_lib);
487 JOIN copy_has_not_been_home ON (true)
491 if ($ctes_needed == 2) {
492 # By this query, we mean to determine that the copy hasn't landed at
493 # home by means of transit during the go-home interval (in addition
494 # to not having circulated from home in the same time frame).
496 # There have been no homebound transits that arrived for this copy
497 # since the beginning of the go-home interval.
500 , copy_has_not_been_home_even_to_idle AS (
501 SELECT result AND NOT (
502 SELECT COUNT(*)::INT::BOOL
503 FROM action.transit_copy atc
505 atc.target_copy = %d AND
506 (atc.dest = %d OR atc.source = %d) AND
507 atc.dest_recv_time >= NOW() - (SELECT value FROM go_home_interval)
508 ) AS result FROM copy_has_not_been_home
509 ) !, $cp->id, $cp->circ_lib, $cp->circ_lib);
510 $joins .= " JOIN copy_has_not_been_home_even_to_idle ON (true) ";
514 join(", ", @clauses),
523 my $here = shift; # just the ID
524 my $cp = shift; # now an object with call_number fleshed,
525 # formerly just copy ID
526 my $limit = int(shift()) || 10;
527 my $age = shift() || '0 seconds';
530 $log->info("deprecated 'fifo' param true, but ignored") if isTrue($fifo);
532 # ScriptBuilder fleshes the circ_lib, which confuses things; ensure we
533 # are working with a circ lib ID and not an object
535 if (ref $cp->circ_lib) {
536 $cp_circ_lib = $cp->circ_lib->id;
538 $cp_circ_lib = $cp->circ_lib;
542 if (ref $cp->call_number->owning_lib) {
543 $cp_owning_lib = $cp->call_number->owning_lib->id;
545 $cp_owning_lib = $cp->call_number->owning_lib;
548 my ($holdsort, $addl_cte, $addl_join) =
549 build_hold_sort_clause(get_hold_sort_order($cp_owning_lib), $cp, $here);
551 local $OpenILS::Application::Storage::WRITE = 1;
553 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $cp_circ_lib, $here, $cp->id, $age);
554 WITH go_home_interval AS (
555 SELECT OILS_JSON_TO_TEXT(
556 (SELECT value FROM actor.org_unit_ancestor_setting(
557 'circ.hold_go_home_interval', ?
559 ))::INTERVAL AS value
563 FROM action.hold_request h
564 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
565 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
566 JOIN actor.usr au ON (au.id = h.usr)
567 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
568 LEFT JOIN actor.usr_standing_penalty ausp
569 ON ( au.id = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
570 LEFT JOIN config.standing_penalty csp
571 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
573 WHERE hm.target_copy = ?
574 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR hm.proximity = 0 OR p.prox = 0)
575 AND h.capture_time IS NULL
576 AND h.cancel_time IS NULL
577 AND (h.expire_time IS NULL OR h.expire_time > NOW())
578 AND h.frozen IS FALSE
580 ORDER BY CASE WHEN h.hold_type IN ('R','F') THEN 0 ELSE 1 END, $holdsort
584 $client->respond( $_ ) for ( @$ids );
587 __PACKAGE__->register_method(
588 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
591 method => 'nearest_hold',
594 sub targetable_holds {
597 my $check_expire = shift;
599 $check_expire ||= '12h';
601 local $OpenILS::Application::Storage::WRITE = 1;
603 # json_query can *almost* represent this query, but can't
604 # handle the CASE statement or the interval arithmetic
605 my $query = <<" SQL";
606 SELECT ahr.id, mmsm.metarecord
607 FROM action.hold_request ahr
608 JOIN reporter.hold_request_record USING (id)
609 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
610 WHERE capture_time IS NULL
611 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
612 AND fulfillment_time IS NULL
613 AND cancel_time IS NULL
615 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
617 my $sth = action::hold_request->db_Main->prepare_cached($query);
618 $sth->execute($check_expire);
619 $client->respond( $_ ) for @{ $sth->fetchall_arrayref };
624 __PACKAGE__->register_method(
625 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
628 method => 'targetable_holds',
630 Returns ordered list of hold request and metarecord IDs
631 for all hold requests that are available for initial targeting
633 @param check interval
634 @return list of pairs of hold request and metarecord IDs
638 sub next_resp_group_id {
642 # XXX This is not replication safe!!!
644 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
645 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
649 __PACKAGE__->register_method(
650 api_name => 'open-ils.storage.action.survey_response.next_group_id',
652 method => 'next_resp_group_id',
655 sub patron_circ_summary {
660 return undef unless ($id);
661 my $c_table = action::circulation->table;
662 my $b_table = money::billing->table;
664 $log->debug("Retrieving patron summary for id $id", DEBUG);
666 my $select = <<" SQL";
667 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
669 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
671 AND c.xact_finish IS NULL
673 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
674 OR c.stop_fines IS NULL
678 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
680 __PACKAGE__->register_method(
681 api_name => 'open-ils.storage.action.circulation.patron_summary',
683 method => 'patron_circ_summary',
686 #XXX Fix stored proc calls
687 sub find_local_surveys {
692 return undef unless ($ou);
693 my $s_table = action::survey->table;
695 my $select = <<" SQL";
698 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
699 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
702 my $sth = action::survey->db_Main->prepare_cached($select);
705 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
709 __PACKAGE__->register_method(
710 api_name => 'open-ils.storage.action.survey.all',
713 method => 'find_local_surveys',
716 #XXX Fix stored proc calls
717 sub find_opac_surveys {
722 return undef unless ($ou);
723 my $s_table = action::survey->table;
725 my $select = <<" SQL";
728 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
729 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
733 my $sth = action::survey->db_Main->prepare_cached($select);
736 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
740 __PACKAGE__->register_method(
741 api_name => 'open-ils.storage.action.survey.opac',
744 method => 'find_opac_surveys',
751 my $limit = shift || 10;
752 my $offset = shift || 0;
754 return undef unless ($ou);
755 my $h_table = action::hold_request->table;
756 my $a_table = asset::copy->table;
757 my $ord_table = asset::copy_location_order->table;
759 my $idlist = 1 if ($self->api_name =~/id_list/o);
760 my $count = 1 if ($self->api_name =~/count$/o);
762 my $status_filter = '';
763 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
765 my $select = <<" SQL";
768 JOIN $a_table a ON (h.current_copy = a.id)
769 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
771 AND h.capture_time IS NULL
772 AND h.cancel_time IS NULL
773 AND (h.expire_time IS NULL OR h.expire_time > NOW())
776 FROM actor.usr_standing_penalty ausp
777 JOIN config.standing_penalty csp ON (
778 csp.id = ausp.standing_penalty
779 AND csp.block_list LIKE '%CAPTURE%'
781 WHERE h.usr = ausp.usr
782 AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() )
785 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
792 SELECT count(DISTINCT h.id)
794 JOIN $a_table a ON (h.current_copy = a.id)
796 AND h.capture_time IS NULL
797 AND h.cancel_time IS NULL
798 AND (h.expire_time IS NULL OR h.expire_time > NOW())
801 FROM actor.usr_standing_penalty ausp
802 JOIN config.standing_penalty csp ON (
803 csp.id = ausp.standing_penalty
804 AND csp.block_list LIKE '%CAPTURE%'
806 WHERE h.usr = ausp.usr
807 AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() )
813 my $sth = action::survey->db_Main->prepare_cached($select);
817 $client->respond( $sth->fetchall_arrayref()->[0][0] );
819 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
821 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
826 __PACKAGE__->register_method(
827 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
831 "Returns a count of holds for a specific library's pull list.",
832 [ [org_unit => "The library's org id", "number"] ],
833 ['A count of holds for the stated library to pull ', 'number']
835 method => 'hold_pull_list',
837 __PACKAGE__->register_method(
838 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
842 "Returns a status filtered count of holds for a specific library's pull list.",
843 [ [org_unit => "The library's org id", "number"] ],
844 ['A status filtered count of holds for the stated library to pull ', 'number']
846 method => 'hold_pull_list',
848 __PACKAGE__->register_method(
849 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
853 "Returns the hold ids for a specific library's pull list.",
854 [ [org_unit => "The library's org id", "number"],
855 [limit => 'An optional page size, defaults to 10', 'number'],
856 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
858 ['A list of holds for the stated library to pull for', 'array']
860 method => 'hold_pull_list',
862 __PACKAGE__->register_method(
863 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
867 "Returns the holds for a specific library's pull list.",
868 [ [org_unit => "The library's org id", "number"],
869 [limit => 'An optional page size, defaults to 10', 'number'],
870 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
872 ['A list of holds for the stated library to pull for', 'array']
874 method => 'hold_pull_list',
876 __PACKAGE__->register_method(
877 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
881 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
882 [ [org_unit => "The library's org id", "number"],
883 [limit => 'An optional page size, defaults to 10', 'number'],
884 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
886 ['A list of holds for the stated library to pull for', 'array']
888 method => 'hold_pull_list',
890 __PACKAGE__->register_method(
891 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
895 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
896 [ [org_unit => "The library's org id", "number"],
897 [limit => 'An optional page size, defaults to 10', 'number'],
898 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
900 ['A list of holds for the stated library to pull for', 'array']
902 method => 'hold_pull_list',
905 sub find_optional_surveys {
910 return undef unless ($ou);
911 my $s_table = action::survey->table;
913 my $select = <<" SQL";
916 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
917 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
918 AND s.required IS FALSE;
921 my $sth = action::survey->db_Main->prepare_cached($select);
924 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
928 __PACKAGE__->register_method(
929 api_name => 'open-ils.storage.action.survey.optional',
932 method => 'find_optional_surveys',
935 sub find_required_surveys {
940 return undef unless ($ou);
941 my $s_table = action::survey->table;
943 my $select = <<" SQL";
946 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
947 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
948 AND s.required IS TRUE;
951 my $sth = action::survey->db_Main->prepare_cached($select);
954 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
958 __PACKAGE__->register_method(
959 api_name => 'open-ils.storage.action.survey.required',
962 method => 'find_required_surveys',
965 sub find_usr_summary_surveys {
970 return undef unless ($ou);
971 my $s_table = action::survey->table;
973 my $select = <<" SQL";
976 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
977 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
978 AND s.usr_summary IS TRUE;
981 my $sth = action::survey->db_Main->prepare_cached($select);
984 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
988 __PACKAGE__->register_method(
989 api_name => 'open-ils.storage.action.survey.usr_summary',
992 method => 'find_usr_summary_surveys',
1001 my $editor = new_editor;
1004 # if ($circ = action::circulation->search_where( { id => $circ_id, stop_fines => undef } )) {
1005 # $circ = action::circulation->retrieve($circ_id)->to_fieldmapper;
1006 # } elsif ($circ = booking::reservation->search_where( { id => $circ_id, return_time => undef, cancel_time => undef } )) {
1007 # $circ = booking::reservation->retrieve($circ_id)->to_fieldmapper;
1009 # $circs = [$circ] if ($circ);
1010 $circs = $editor->search_action_circulation( { id => $circ_id, stop_fines => undef } );
1012 $circs = $editor->search_booking_reservation->search_where( { id => $circ_id, return_time => undef, cancel_time => undef } );
1015 $circs = [map { $_->to_fieldmapper } overdue_circs(undef, 1, 1, 1)];
1018 return OpenILS::Application::Circ::CircCommon->generate_fines({circs => $circs, conn => $client})
1020 __PACKAGE__->register_method(
1021 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1024 method => 'generate_fines',
1028 sub MR_records_matching_format {
1034 # include all visible copies, regardless of holdability
1035 my $opac_visible = shift;
1037 # find filters for MR holds
1039 if (defined($filter)) {
1040 ($mr_filter) = @{action::hold_request->db_Main->selectcol_arrayref(
1041 'SELECT metabib.compile_composite_attr(?)',
1047 my $records = [metabib::metarecord->retrieve($MR)->source_records];
1049 my $vis_q = 'asset.record_has_holdable_copy(?,?)';
1050 if ($opac_visible) {
1053 SELECT 1 FROM asset.opac_visible_copies
1054 WHERE record = ? AND circ_lib IN (
1055 SELECT id FROM actor.org_unit_descendants(?)
1061 my $q = "SELECT source FROM metabib.record_attr_vector_list WHERE source = ? AND vlist @@ ? AND $vis_q";
1062 my @args = ( $mr_filter, $org );
1064 $q = "SELECT true WHERE $vis_q";
1068 for my $r ( map { isTrue($_->deleted) ? () : ($_->id) } @$records ) {
1069 # the map{} below is tricky. it puts the record ID in front of each param. see $q above
1070 $client->respond($r)
1071 if @{action::hold_request->db_Main->selectcol_arrayref( $q, {}, map { ( $r => $_ ) } @args )};
1074 return; # discard final l-val
1076 __PACKAGE__->register_method(
1077 api_name => 'open-ils.storage.metarecord.filtered_records',
1081 method => 'MR_records_matching_format',
1085 sub new_hold_copy_targeter {
1088 my $check_expire = shift;
1089 my $one_hold = shift;
1090 my $find_copy = shift;
1092 local $OpenILS::Application::Storage::WRITE = 1;
1094 $self->{target_weight} = {};
1095 $self->{max_loops} = {};
1101 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1102 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
1103 } elsif ( $check_expire ) {
1105 # what's the retarget time threashold?
1107 $check_expire ||= '12h';
1108 $check_expire = interval_to_seconds( $check_expire );
1110 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1113 my $expire_threshold = sprintf(
1114 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1115 $year, $mon, $mday, $hour, $min, $sec
1118 # find all the holds holds needing retargeting
1119 $holds = [ action::hold_request->search_where(
1120 { capture_time => undef,
1121 fulfillment_time => undef,
1122 cancel_time => undef,
1124 prev_check_time => { '<=' => $expire_threshold },
1126 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
1128 # find all the holds holds needing first time targeting
1129 push @$holds, action::hold_request->search(
1130 capture_time => undef,
1131 fulfillment_time => undef,
1132 prev_check_time => undef,
1134 cancel_time => undef,
1135 { order_by => 'selection_depth DESC, request_time' } );
1138 # find all the holds holds needing first time targeting ONLY
1139 $holds = [ action::hold_request->search(
1140 capture_time => undef,
1141 fulfillment_time => undef,
1142 prev_check_time => undef,
1143 cancel_time => undef,
1145 { order_by => 'selection_depth DESC, request_time' } ) ];
1147 } catch Error with {
1149 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1152 my @closed = actor::org_unit::closed_date->search_where(
1153 { close_start => { '<=', 'now' },
1154 close_end => { '>=', 'now' } }
1157 if ($check_expire) {
1159 # $check_expire, if it exists, was already converted to seconds
1160 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1164 my $next_check_time = sprintf(
1165 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1166 $year, $mon, $mday, $hour, $min, $sec
1170 my @closed_at_next = actor::org_unit::closed_date->search_where(
1171 { close_start => { '<=', $next_check_time },
1172 close_end => { '>=', $next_check_time } }
1176 for my $c_at_n (@closed_at_next) {
1177 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1178 push @new_closed, $c_at_n;
1181 @closed = @new_closed;
1185 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1186 my $editor = new_editor;
1188 my $target_when_closed = {};
1189 my $target_when_closed_if_at_pickup_lib = {};
1191 for my $hold (@$holds) {
1193 #start a transaction if needed
1194 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1195 $log->debug("Cleaning up after previous transaction\n");
1196 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1198 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1199 $log->info("Processing hold ".$hold->id."...\n");
1201 #first, re-fetch the hold, to make sure it's not captured already
1202 $hold->remove_from_object_index();
1203 $hold = action::hold_request->retrieve( $hold->id );
1205 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1207 # remove old auto-targeting maps
1208 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1209 $_->delete for (@oldmaps);
1211 if ($hold->expire_time) {
1212 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1213 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1215 # cancel cause = un-targeted expiration
1216 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1218 # refresh fields from the DB while still in the xact
1219 my $fm_hold = $hold->to_fieldmapper;
1221 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1223 # tell A/T the hold was cancelled
1224 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1225 $ses->request('open-ils.trigger.event.autocreate',
1226 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1232 my $all_copies = [];
1234 # find all the potential copies
1235 if ($hold->hold_type eq 'M') {
1237 $self->method_lookup(
1238 'open-ils.storage.metarecord.filtered_records'
1239 )->run( $hold->target, $hold->holdable_formats )
1242 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1243 ->run( $r_id, $hold->selection_ou, $hold->selection_depth );
1245 for my $cn ( @{ $rtree->call_numbers } ) {
1247 asset::copy->search_where(
1248 { id => [map {$_->id} @{ $cn->copies }],
1250 ) if ($cn && @{ $cn->copies });
1253 } elsif ($hold->hold_type eq 'T') {
1255 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1256 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1259 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1263 for my $cn ( @{ $rtree->call_numbers } ) {
1265 asset::copy->search_where(
1266 { id => [map {$_->id} @{ $cn->copies }],
1268 ) if ($cn && @{ $cn->copies });
1270 } elsif ($hold->hold_type eq 'V') {
1272 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1273 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1276 asset::copy->search_where(
1277 { id => [map {$_->id} @{ $vtree->copies }],
1279 ) if ($vtree && @{ $vtree->copies });
1281 } elsif ($hold->hold_type eq 'P') {
1282 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1284 asset::copy->search_where(
1285 { id => [map {$_->target_copy} @part_maps],
1290 } elsif ($hold->hold_type eq 'I') {
1292 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1293 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1296 asset::copy->search_where(
1297 { id => [map {$_->unit->id} @{ $itree->items }],
1299 ) if ($itree && @{ $itree->items });
1301 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1302 my $_cp = asset::copy->retrieve($hold->target);
1303 push @$all_copies, $_cp if $_cp;
1306 # Force and recall holds bypass pretty much everything
1307 if ($hold->hold_type ne 'R' && $hold->hold_type ne 'F') {
1309 @$all_copies = grep { isTrue($_->status->holdable) &&
1310 isTrue($_->location->holdable) &&
1311 isTrue($_->holdable) &&
1312 !isTrue($_->deleted) &&
1313 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1314 ( ( $hold->hold_type ne 'C' && $hold->hold_type ne 'I' # Copy-level holds don't care about parts
1315 && $hold->hold_type ne 'P' ) ? $_->part_maps->count == 0 : 1)
1319 # let 'em know we're still working
1320 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1322 # if we have no copies ...
1323 if (!ref $all_copies || !@$all_copies) {
1324 $log->info("\tNo copies available for targeting at all!\n");
1325 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1327 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1328 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1332 my $copy_count = @$all_copies;
1333 my $found_copy = undef;
1334 $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1336 # map the potentials, so that we can pick up checkins
1337 my $hold_copy_map = {};
1338 $hold_copy_map->{$_->hold}->{$_->target_copy} = $_->proximity
1341 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } )
1345 my $pu_lib = ''.$hold->pickup_lib;
1346 my $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
1347 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1349 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1352 for my $c (@$all_copies) {
1354 next if ($hold->current_copy and $c->id eq $hold->current_copy);
1356 # skip on circ lib is closed IFF we care
1359 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1360 $ignore_closing = ou_ancestor_setting_value_or_cache(
1363 'circ.holds.target_when_closed_if_at_pickup_lib',
1364 $target_when_closed_if_at_pickup_lib
1367 if (not $ignore_closing) { # one more chance to find a reason
1368 # to ignore OU closedness.
1369 $ignore_closing = ou_ancestor_setting_value_or_cache(
1372 'circ.holds.target_when_closed',
1378 # "For hold " . $hold->id . " and copy with circ_lib " .
1379 # $c->circ_lib . " we " .
1380 # ($ignore_closing ? "ignore" : "respect")
1385 (not $ignore_closing) and
1386 (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1389 # target of another hold
1390 next if (action::hold_request
1392 { current_copy => $c->id,
1393 fulfillment_time => undef,
1394 cancel_time => undef,
1399 # we passed all three, keep it
1400 push @good_copies, $c if ($c);
1401 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1404 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1406 my $old_best = $hold->current_copy;
1407 my $old_best_still_valid = 0; # Assume no, but the next line says yes if it is still a potential.
1408 $old_best_still_valid = 1 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies );
1409 $hold->update({ current_copy => undef }) if ($old_best);
1411 if (!scalar(@good_copies)) {
1412 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1413 if ( $old_best_still_valid ) {
1414 # the old copy is still available
1415 $log->debug("\tPushing current_copy back onto the targeting list");
1416 push @good_copies, $old_best;
1418 # oops, old copy is not available
1419 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1420 $hold->update( { prev_check_time => 'today' } );
1421 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1422 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1427 # reset prox list after trimming good copies
1428 $prox_list = create_prox_list(
1430 [ grep { $_->status == 0 || $_->status == 7 } @good_copies ],
1431 $hold, $hold_copy_map
1434 $all_copies = [ grep { ''.$_->circ_lib ne $pu_lib && ( $_->status == 0 || $_->status == 7 ) } @good_copies ];
1436 my $min_prox = [ sort keys %$prox_list ]->[0];
1438 if ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') { # Recall/Force holds bypass hold rules.
1439 $best = $good_copies[0] if(scalar @good_copies);
1441 $best = choose_nearest_copy($hold, { $min_prox => delete($$prox_list{$min_prox}) });
1444 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1447 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1449 $self->{max_loops}{$pu_lib} = $U->ou_ancestor_setting(
1450 $pu_lib, 'circ.holds.max_org_unit_target_loops', $editor
1453 if (defined($self->{max_loops}{$pu_lib})) {
1454 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1456 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1457 my $circ_lib_list = [keys %circ_lib_map];
1459 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1461 # Grab the "biggest" loop for this hold so far
1462 my $current_loop = $cstore->request(
1463 'open-ils.cstore.json_query',
1465 select => { aufhmxl => ['max'] },
1467 where => { hold => $hold->id}
1471 $current_loop = $current_loop->{max} if ($current_loop);
1472 $current_loop ||= 1;
1474 my $exclude_list = $cstore->request(
1475 'open-ils.cstore.json_query.atomic',
1477 select => { aufhol => ['circ_lib'] },
1479 where => { hold => $hold->id}
1484 if ($exclude_list && @$exclude_list) {
1485 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1486 # check to see if we've used up every library in the potentials list
1487 for my $l ( @$circ_lib_list ) {
1489 for my $ex ( @$exclude_list ) {
1495 push(@keepers, $l) if ($keep);
1498 @keepers = @$circ_lib_list;
1501 $current_loop++ if (!@keepers);
1503 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1504 # We haven't exceeded max_loops yet
1506 for my $cp ( @$all_copies ) {
1507 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1510 $all_copies = [@keeper_copies];
1512 # We have, and should remove potentials and cancel the hold
1513 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1514 $_->delete for (@oldmaps);
1516 # cancel cause = un-targeted expiration
1517 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1519 # refresh fields from the DB while still in the xact
1520 my $fm_hold = $hold->to_fieldmapper;
1522 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1524 # tell A/T the hold was cancelled
1525 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1526 $ses->request('open-ils.trigger.event.autocreate',
1527 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1532 $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
1534 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1538 $best = choose_nearest_copy($hold, $prox_list);
1541 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1543 # hold wasn't fulfilled, record the fact
1545 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1546 action::unfulfilled_hold_list->create(
1547 { hold => ''.$hold->id,
1548 current_copy => ''.$old_best->id,
1549 circ_lib => ''.$old_best->circ_lib,
1554 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1555 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1557 $old_best_still_valid &&
1558 !action::hold_request
1560 { current_copy => $old_best->id,
1561 fulfillment_time => undef,
1562 cancel_time => undef,
1565 ( OpenILS::Utils::PermitHold::permit_copy_hold(
1566 { title => $old_best->call_number->record->to_fieldmapper,
1567 patron => $hold->usr->to_fieldmapper,
1568 copy => $old_best->to_fieldmapper,
1569 requestor => $hold->requestor->to_fieldmapper,
1570 request_lib => $hold->request_lib->to_fieldmapper,
1571 pickup_lib => $hold->pickup_lib->id,
1576 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1577 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1579 $hold->update( { prev_check_time => 'now' } );
1580 $log->info( "\tThere were no targetable copies for the hold" );
1581 process_recall($actor, $log, $hold, \@good_copies);
1584 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1585 $log->info("\tProcessing of hold ".$hold->id." complete.");
1588 { hold => $hold->id,
1589 old_target => ($old_best ? $old_best->id : undef),
1590 eligible_copies => $copy_count,
1591 target => ($best ? $best->id : undef),
1592 found_copy => $found_copy };
1597 $log->error("Processing of hold failed: $e");
1598 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1599 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1606 __PACKAGE__->register_method(
1607 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1609 method => 'new_hold_copy_targeter',
1612 sub process_recall {
1613 my ($actor, $log, $hold, $good_copies) = @_;
1615 # Bail early if we don't have required settings to avoid spurious requests
1616 my ($recall_threshold, $return_interval, $fine_rules);
1618 my $rv = $actor->request(
1619 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1623 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1626 $recall_threshold = $rv->{value};
1628 $rv = $actor->request(
1629 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1633 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1636 $return_interval = $rv->{value};
1638 $rv = $actor->request(
1639 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1643 $fine_rules = $rv->{value};
1646 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1648 # We want checked out copies (status = 1) at the hold pickup lib
1649 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1651 my @copy_ids = map { $_->id } @$all_copies;
1653 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1655 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1657 # Iterate over the checked-out copies to find a copy with a
1658 # loan period longer than the recall threshold:
1659 my $circs = [ action::circulation->search_where(
1660 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1661 { order_by => 'due_date ASC' }
1664 # If we have a candidate copy, then:
1665 if (scalar(@$circs)) {
1666 my $circ = $circs->[0];
1667 $log->info("Recalling circ ID : " . $circ->id);
1669 # Give the user a new due date of either a full recall threshold,
1670 # or the return interval, whichever is further in the future
1671 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1672 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1673 $return_date = $threshold_date;
1676 my $update_fields = {
1677 due_date => $return_date,
1678 renewal_remaining => 0,
1681 # If the OU hasn't defined new fine rules for recalls, keep them
1684 $log->info("Apply recall fine rules: $fine_rules");
1685 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1686 $update_fields->{recurring_fine} = $rules->[0];
1687 $update_fields->{fine_interval} = $rules->[1];
1688 $update_fields->{max_fine} = $rules->[2];
1691 # Adjust circ for current user
1692 $circ->update($update_fields);
1694 # Create trigger event for notifying current user
1695 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1696 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1699 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1702 sub reservation_targeter {
1705 my $one_reservation = shift;
1707 local $OpenILS::Application::Storage::WRITE = 1;
1712 if ($one_reservation) {
1713 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1714 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1717 # find all the reservations needing targeting
1719 booking::reservation->search_where(
1720 { current_resource => undef,
1721 cancel_time => undef,
1722 start_time => { '>' => 'now' }
1724 { order_by => 'start_time' }
1728 } catch Error with {
1730 die "Could not retrieve reservation requests:\n\n$e\n";
1734 for my $bresv (@$reservations) {
1736 #start a transaction if needed
1737 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1738 $log->debug("Cleaning up after previous transaction\n");
1739 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1741 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1742 $log->info("Processing reservation ".$bresv->id."...\n");
1744 #first, re-fetch the hold, to make sure it's not captured already
1745 $bresv->remove_from_object_index();
1746 $bresv = booking::reservation->retrieve( $bresv->id );
1748 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1750 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1751 if (DateTime->compare($end_time, DateTime->now) < 0) {
1753 # cancel cause = un-targeted expiration
1754 $bresv->update( { cancel_time => 'now' } );
1756 # refresh fields from the DB while still in the xact
1757 my $fm_bresv = $bresv->to_fieldmapper;
1759 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1761 # tell A/T the reservation was cancelled
1762 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1763 $ses->request('open-ils.trigger.event.autocreate',
1764 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1769 my $possible_resources;
1771 # find all the potential resources
1772 if (!$bresv->target_resource) {
1773 my $filter = { type => $bresv->target_resource_type };
1774 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1776 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1778 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1779 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1780 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1782 $possible_resources = $bresv->target_resource;
1785 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1786 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1789 my @good_resources = ();
1791 for my $res (@$all_resources) {
1792 unless (isTrue($res->type->catalog_item)) {
1793 push @good_resources, $res;
1797 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1800 push @good_resources, $res;
1804 # At this point, if we're just targeting one specific
1805 # resource, just succeed. We don't care about its present
1807 if ($bresv->target_resource) {
1808 push @good_resources, $res;
1812 if ($copy->status->id == 0 || $copy->status->id == 7) {
1813 push @good_resources, $res;
1817 if ($copy->status->id == 1) {
1818 my $circs = [ action::circulation->search_where(
1819 {target_copy => $copy->id, checkin_time => undef },
1820 { order_by => 'id DESC' }
1824 my $due_date = $circs->[0]->due_date;
1825 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1826 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1827 if (DateTime->compare($start_time, $due_date) < 0) {
1828 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1832 push @good_resources, $res;
1838 push @good_resources, $res if (isTrue($copy->status->holdable));
1841 # let 'em know we're still working
1842 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1844 # if we have no copies ...
1845 if (!@good_resources) {
1846 $log->info("\tNo resources available for targeting at all!\n");
1847 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1850 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1854 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1856 # LFW: note that after the inclusion of hold proximity
1857 # adjustment, this prox_list is the only prox_list
1858 # array in this perl package. Other occurences are
1864 $_->owner == $bresv->pickup_lib
1868 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1869 # $all_copies is now a list of copies not at the pickup library
1871 my $best = shift @good_resources;
1872 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1875 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1879 sort { $a->[0] <=> $b->[0] }
1881 [ actor::org_unit_proximity->search_where(
1882 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1888 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1890 $best = shift @$prox_list
1894 $bresv->update( { current_resource => ''.$best->id } );
1895 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1898 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1899 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1902 { reservation => $bresv->id,
1903 current_resource => ($best ? $best->id : undef) };
1908 $log->error("Processing of bresv failed: $e");
1909 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1910 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1917 __PACKAGE__->register_method(
1918 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1920 method => 'reservation_targeter',
1925 my %cache = (titles => {}, cns => {});
1927 sub copy_hold_capture {
1932 if (!defined($cps)) {
1934 $cps = [ asset::copy->search( id => $hold->target ) ];
1935 } catch Error with {
1937 die "Could not retrieve initial volume list:\n\n$e\n";
1941 my @copies = grep { $_->holdable } @$cps;
1943 for (my $i = 0; $i < @$cps; $i++) {
1944 next unless $$cps[$i];
1946 my $cn = $cache{cns}{$copies[$i]->call_number};
1947 my $rec = $cache{titles}{$cn->record};
1948 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1949 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1950 $copies[$i] = undef if (
1952 !$self->{user_filter}->request(
1953 'open-ils.circ.permit_hold',
1954 $hold->to_fieldmapper, do {
1955 my $cp_fm = $copies[$i]->to_fieldmapper;
1956 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1957 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1958 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1961 { title => $rec->to_fieldmapper,
1962 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1963 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1966 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1969 @copies = grep { $_ } @copies;
1971 my $count = @copies;
1973 return unless ($count);
1975 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1978 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1979 for my $c (@copies) {
1980 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1982 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1988 sub choose_nearest_copy {
1990 my $prox_list = shift;
1992 for my $p ( sort keys %$prox_list ) {
1993 next unless (ref $$prox_list{$p});
1995 my @capturable = @{ $$prox_list{$p} };
1996 next unless (@capturable);
1998 my $rand = int(rand(scalar(@capturable)));
2000 while (my ($c) = splice(@capturable, $rand, 1)) {
2001 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
2002 { title => $c->call_number->record->to_fieldmapper,
2003 patron => $hold->usr->to_fieldmapper,
2004 copy => $c->to_fieldmapper,
2005 requestor => $hold->requestor->to_fieldmapper,
2006 request_lib => $hold->request_lib->to_fieldmapper,
2007 pickup_lib => $hold->pickup_lib->id,
2013 last unless(@capturable);
2014 $rand = int(rand(scalar(@capturable)));
2019 sub create_prox_list {
2024 my $hold_copy_map = shift || {};
2027 my $editor = new_editor;
2028 for my $cp (@$copies) {
2029 my $prox = $hold_copy_map->{"$hold"}->{"$cp"}; # Allow CDBI stringification to get the pkey
2030 ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib, $hold ) unless (defined $prox);
2031 next unless (defined($prox));
2033 my $copy_circ_lib = ''.$cp->circ_lib;
2034 # Fetch the weighting value for hold targeting, defaulting to 1
2035 $self->{target_weight}{$copy_circ_lib} ||= $U->ou_ancestor_setting(
2036 $copy_circ_lib.'', 'circ.holds.org_unit_target_weight', $editor
2038 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
2039 $self->{target_weight}{$copy_circ_lib} ||= 1;
2041 $prox_list{$prox} = [] unless defined($prox_list{$prox});
2042 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
2043 push @{$prox_list{$prox}}, $cp;
2049 sub volume_hold_capture {
2054 if (!defined($vols)) {
2056 $vols = [ asset::call_number->search( id => $hold->target ) ];
2057 $cache{cns}{$_->id} = $_ for (@$vols);
2058 } catch Error with {
2060 die "Could not retrieve initial volume list:\n\n$e\n";
2064 my @v_ids = map { $_->id } @$vols;
2068 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
2070 } catch Error with {
2072 warn "Could not retrieve copy list:\n\n$e\n";
2075 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
2078 sub title_hold_capture {
2083 if (!defined($titles)) {
2085 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
2086 $cache{titles}{$_->id} = $_ for (@$titles);
2087 } catch Error with {
2089 die "Could not retrieve initial title list:\n\n$e\n";
2093 my @t_ids = map { $_->id } @$titles;
2096 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
2098 } catch Error with {
2100 warn "Could not retrieve volume list:\n\n$e\n";
2103 $cache{cns}{$_->id} = $_ for (@$cn_list);
2105 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);