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',
152 my $upper_interval = shift || '1 millennium';
155 my $c_t = action::circulation->table;
160 WHERE stop_fines IS NULL
161 AND due_date < ( CURRENT_TIMESTAMP - grace_period )
162 AND fine_interval < ?::INTERVAL
165 my $sth = action::circulation->db_Main->prepare_cached($sql);
166 $sth->execute($upper_interval);
168 my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
170 $c_t = booking::reservation->table;
174 WHERE return_time IS NULL
175 AND end_time < ( CURRENT_TIMESTAMP )
176 AND fine_interval IS NOT NULL
177 AND cancel_time IS NULL
180 $sth = action::circulation->db_Main->prepare_cached($sql);
183 push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
188 sub complete_reshelving {
193 local $OpenILS::Application::Storage::WRITE = 1;
195 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
196 unless (interval_to_seconds( $window ));
198 my $cp = asset::copy->table;
207 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)
210 my $sth = action::circulation->db_Main->prepare_cached($sql);
211 $sth->execute($window);
216 __PACKAGE__->register_method(
217 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
220 method => 'complete_reshelving',
223 sub mark_longoverdue {
228 local $OpenILS::Application::Storage::WRITE = 1;
230 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
231 unless (interval_to_seconds( $window ));
233 my $setting = actor::org_unit_setting->table;
234 my $circ = action::circulation->table;
238 SET stop_fines = 'LONGOVERDUE',
239 stop_fines_time = now()
243 LEFT JOIN $setting setting
244 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
245 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
246 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
250 my $sth = action::circulation->db_Main->prepare_cached($sql);
251 $sth->execute($window);
256 __PACKAGE__->register_method(
257 api_name => 'open-ils.storage.action.circulation.long_overdue',
260 method => 'mark_longoverdue',
263 sub auto_thaw_frozen_holds {
267 local $OpenILS::Application::Storage::WRITE = 1;
269 my $holds = action::hold_request->table;
271 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
273 my $sth = action::hold_request->db_Main->prepare_cached($sql);
279 __PACKAGE__->register_method(
280 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
284 method => 'auto_thaw_frozen_holds',
291 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
293 $client->respond( $idlist ? $_ : $_->to_fieldmapper ) for ( overdue_circs('', $idlist) );
298 __PACKAGE__->register_method(
299 api_name => 'open-ils.storage.action.circulation.overdue',
302 method => 'grab_overdue',
304 Return list of overdue circulations and reservations to be used for fine generation.
305 Despite the name, this is not a generic method for retrieving all overdue loans,
306 as it excludes loans that have already hit the maximum fine limit.
309 __PACKAGE__->register_method(
310 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
313 method => 'grab_overdue',
316 sub get_hold_sort_order {
319 my $dbh = action::hold_request->db_Main;
321 # The purpose of this function is to return column names in a DB-configured
322 # order, so it won't do to add columns here or change column names unless
323 # you also change the expectation of anything calling this function.
325 my $row = $dbh->selectrow_hashref(
328 cbho.pprox, cbho.hprox, cbho.aprox, cbho.approx, cbho.priority,
329 cbho.cut, cbho.depth, cbho.htime, cbho.shtime, cbho.rtime
330 FROM config.best_hold_order cbho
332 SELECT oils_json_to_text(value)::INT
333 FROM actor.org_unit_ancestor_setting('circ.hold_capture_order', ?)
337 pprox => 1, hprox => 8, aprox => 2, priority => 3,
338 cut => 4, depth => 5, htime => 7, rtime => 6
341 # Return only the keys of our hash, sorted by value,
342 # keys for null values omitted.
344 grep { defined $row->{$_} } (
345 sort {$row->{$a} cmp $row->{$b}} keys %$row
350 # Returns an ORDER BY clause
351 # *and* a string with a CTE expression to precede the nearest-hold SQL query
352 # *and* a string with extra JOIN statements needed
353 sub build_hold_sort_clause {
354 my ($columns, $cp, $here) = @_;
356 my %order_by_sprintf_args = (
357 hprox => [$cp->call_number->owning_lib],
358 approx => [$cp->id, $here],
359 htime => [$cp->call_number->owning_lib, $cp->call_number->owning_lib],
360 shtime => [$cp->call_number->owning_lib, $cp->call_number->owning_lib]
365 foreach my $col (@$columns) {
366 if ($col eq 'htime' and not $ctes_needed) {
368 } elsif ($col eq 'shtime') {
373 @args = @{$order_by_sprintf_args{$col}} if
374 exists $order_by_sprintf_args{$col};
376 push @clauses, sprintf($HOLD_SORT_ORDER_BY{$col}, @args);
378 last if $col eq 'rtime'; # rtime is effectively unique, no need for
379 # more order-by clauses after that.
382 my ($ctes, $joins) = ("", "");
383 if ($ctes_needed >= 1) {
384 # Each CTE serves the next. The first is one version or another
385 # of last_event_on_copy, which is described in holds-go-home.txt
386 # TechRef, but it essentially returns place and time of the most
387 # recent transit or circ to do with a copy, and failing that it
388 # returns a synthetic event that means "here" and "now".
390 if ($ctes_needed == 2) {
392 , last_event_on_copy AS ( -- combined circ and transit version
398 COALESCE(dest_recv_time, source_send_time) AS moment
399 FROM action.transit_copy
400 WHERE target_copy = %d
401 ORDER BY moment DESC LIMIT 1
405 COALESCE(checkin_lib, circ_lib) AS place,
406 COALESCE(checkin_time, xact_start) AS moment
407 FROM action.circulation
408 WHERE target_copy = %d
409 ORDER BY moment DESC LIMIT 1
415 ) x ORDER BY concrete DESC, moment DESC LIMIT 1
416 ) !, $cp->id, $cp->id, $cp->call_number->owning_lib);
419 , last_event_on_copy AS ( -- circ only version
423 COALESCE(checkin_lib, circ_lib) AS place,
424 COALESCE(checkin_time, xact_start) AS moment
425 FROM action.circulation
426 WHERE target_copy = %d
427 ORDER BY moment DESC LIMIT 1
432 ) x ORDER BY concrete DESC, moment DESC LIMIT 1
433 ) !, $cp->id, $cp->call_number->owning_lib);
437 JOIN last_event_on_copy ON (true)
440 # For our next auxiliary query, the question we seek to answer is,
441 # "has our copy been circulating away from home too long?"
443 # Have there been no checkouts at the copy's circ_lib since the
444 # beginning of our go-home interval?
446 # [We use sprintf because the outer function that's going to send one
447 # big query through DBI is blind to our process of dynamically building
448 # these CTEs, and it wouldn't know what bind parameters to pass unless
449 # we did a lot more work here. This is injection-safe because we only
450 # use the %d formatter.]
452 , copy_has_not_been_home AS (
455 SELECT MIN(circ.id) FROM action.circulation circ
456 JOIN go_home_interval ON (true)
458 circ.target_copy = %d AND
459 circ.circ_lib = %d AND
460 circ.xact_start >= NOW() - go_home_interval.value
462 ) !, $cp->id, $cp->circ_lib);
465 JOIN copy_has_not_been_home ON (true)
469 if ($ctes_needed == 2) {
470 # By this query, we mean to determine that the copy hasn't landed at
471 # home by means of transit during the go-home interval (in addition
472 # to not having circulated from home in the same time frame).
474 # There have been no homebound transits that arrived for this copy
475 # since the beginning of the go-home interval.
478 , copy_has_not_been_home_even_to_idle AS (
479 SELECT result AND NOT (
480 SELECT COUNT(*)::INT::BOOL
481 FROM action.transit_copy atc
483 atc.target_copy = %d AND
484 (atc.dest = %d OR atc.source = %d) AND
485 atc.dest_recv_time >= NOW() - (SELECT value FROM go_home_interval)
486 ) AS result FROM copy_has_not_been_home
487 ) !, $cp->id, $cp->circ_lib, $cp->circ_lib);
488 $joins .= " JOIN copy_has_not_been_home_even_to_idle ON (true) ";
492 join(", ", @clauses),
501 my $here = shift; # just the ID
502 my $cp = shift; # now an object with call_number fleshed,
503 # formerly just copy ID
504 my $limit = int(shift()) || 10;
505 my $age = shift() || '0 seconds';
508 $log->info("deprecated 'fifo' param true, but ignored") if isTrue($fifo);
510 # ScriptBuilder fleshes the circ_lib, which confuses things; ensure we
511 # are working with a circ lib ID and not an object
513 if (ref $cp->circ_lib) {
514 $cp_circ_lib = $cp->circ_lib->id;
516 $cp_circ_lib = $cp->circ_lib;
520 if (ref $cp->call_number->owning_lib) {
521 $cp_owning_lib = $cp->call_number->owning_lib->id;
523 $cp_owning_lib = $cp->call_number->owning_lib;
526 my ($holdsort, $addl_cte, $addl_join) =
527 build_hold_sort_clause(get_hold_sort_order($cp_owning_lib), $cp, $here);
529 local $OpenILS::Application::Storage::WRITE = 1;
531 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $cp_circ_lib, $here, $cp->id, $age);
532 WITH go_home_interval AS (
533 SELECT OILS_JSON_TO_TEXT(
534 (SELECT value FROM actor.org_unit_ancestor_setting(
535 'circ.hold_go_home_interval', ?
537 ))::INTERVAL AS value
541 FROM action.hold_request h
542 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
543 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
544 JOIN actor.usr au ON (au.id = h.usr)
545 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
546 LEFT JOIN actor.usr_standing_penalty ausp
547 ON ( au.id = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
548 LEFT JOIN config.standing_penalty csp
549 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
551 WHERE hm.target_copy = ?
552 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR hm.proximity = 0 OR p.prox = 0)
553 AND h.capture_time IS NULL
554 AND h.cancel_time IS NULL
555 AND (h.expire_time IS NULL OR h.expire_time > NOW())
556 AND h.frozen IS FALSE
558 ORDER BY CASE WHEN h.hold_type IN ('R','F') THEN 0 ELSE 1 END, $holdsort
562 $client->respond( $_ ) for ( @$ids );
565 __PACKAGE__->register_method(
566 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
569 method => 'nearest_hold',
572 sub targetable_holds {
575 my $check_expire = shift;
577 $check_expire ||= '12h';
579 local $OpenILS::Application::Storage::WRITE = 1;
581 # json_query can *almost* represent this query, but can't
582 # handle the CASE statement or the interval arithmetic
583 my $query = <<" SQL";
584 SELECT ahr.id, mmsm.metarecord
585 FROM action.hold_request ahr
586 JOIN reporter.hold_request_record USING (id)
587 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
588 WHERE capture_time IS NULL
589 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
590 AND fulfillment_time IS NULL
591 AND cancel_time IS NULL
593 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
595 my $sth = action::hold_request->db_Main->prepare_cached($query);
596 $sth->execute($check_expire);
597 $client->respond( $_ ) for @{ $sth->fetchall_arrayref };
602 __PACKAGE__->register_method(
603 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
606 method => 'targetable_holds',
608 Returns ordered list of hold request and metarecord IDs
609 for all hold requests that are available for initial targeting
611 @param check interval
612 @return list of pairs of hold request and metarecord IDs
616 sub next_resp_group_id {
620 # XXX This is not replication safe!!!
622 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
623 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
627 __PACKAGE__->register_method(
628 api_name => 'open-ils.storage.action.survey_response.next_group_id',
630 method => 'next_resp_group_id',
633 sub patron_circ_summary {
638 return undef unless ($id);
639 my $c_table = action::circulation->table;
640 my $b_table = money::billing->table;
642 $log->debug("Retrieving patron summary for id $id", DEBUG);
644 my $select = <<" SQL";
645 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
647 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
649 AND c.xact_finish IS NULL
651 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
652 OR c.stop_fines IS NULL
656 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
658 __PACKAGE__->register_method(
659 api_name => 'open-ils.storage.action.circulation.patron_summary',
661 method => 'patron_circ_summary',
664 #XXX Fix stored proc calls
665 sub find_local_surveys {
670 return undef unless ($ou);
671 my $s_table = action::survey->table;
673 my $select = <<" SQL";
676 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
677 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
680 my $sth = action::survey->db_Main->prepare_cached($select);
683 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
687 __PACKAGE__->register_method(
688 api_name => 'open-ils.storage.action.survey.all',
691 method => 'find_local_surveys',
694 #XXX Fix stored proc calls
695 sub find_opac_surveys {
700 return undef unless ($ou);
701 my $s_table = action::survey->table;
703 my $select = <<" SQL";
706 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
707 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
711 my $sth = action::survey->db_Main->prepare_cached($select);
714 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
718 __PACKAGE__->register_method(
719 api_name => 'open-ils.storage.action.survey.opac',
722 method => 'find_opac_surveys',
729 my $limit = shift || 10;
730 my $offset = shift || 0;
732 return undef unless ($ou);
733 my $h_table = action::hold_request->table;
734 my $a_table = asset::copy->table;
735 my $ord_table = asset::copy_location_order->table;
737 my $idlist = 1 if ($self->api_name =~/id_list/o);
738 my $count = 1 if ($self->api_name =~/count$/o);
740 my $status_filter = '';
741 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
743 my $select = <<" SQL";
746 JOIN $a_table a ON (h.current_copy = a.id)
747 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
749 AND h.capture_time IS NULL
750 AND h.cancel_time IS NULL
751 AND (h.expire_time IS NULL OR h.expire_time > NOW())
754 FROM actor.usr_standing_penalty ausp
755 JOIN config.standing_penalty csp ON (
756 csp.id = ausp.standing_penalty
757 AND csp.block_list LIKE '%CAPTURE%'
759 WHERE h.usr = ausp.usr
760 AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() )
763 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
770 SELECT count(DISTINCT h.id)
772 JOIN $a_table a ON (h.current_copy = a.id)
774 AND h.capture_time IS NULL
775 AND h.cancel_time IS NULL
776 AND (h.expire_time IS NULL OR h.expire_time > NOW())
779 FROM actor.usr_standing_penalty ausp
780 JOIN config.standing_penalty csp ON (
781 csp.id = ausp.standing_penalty
782 AND csp.block_list LIKE '%CAPTURE%'
784 WHERE h.usr = ausp.usr
785 AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() )
791 my $sth = action::survey->db_Main->prepare_cached($select);
795 $client->respond( $sth->fetchall_arrayref()->[0][0] );
797 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
799 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
804 __PACKAGE__->register_method(
805 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
809 "Returns a count of holds for a specific library's pull list.",
810 [ [org_unit => "The library's org id", "number"] ],
811 ['A count of holds for the stated library to pull ', 'number']
813 method => 'hold_pull_list',
815 __PACKAGE__->register_method(
816 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
820 "Returns a status filtered count of holds for a specific library's pull list.",
821 [ [org_unit => "The library's org id", "number"] ],
822 ['A status filtered count of holds for the stated library to pull ', 'number']
824 method => 'hold_pull_list',
826 __PACKAGE__->register_method(
827 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
831 "Returns the hold ids for a specific library's pull list.",
832 [ [org_unit => "The library's org id", "number"],
833 [limit => 'An optional page size, defaults to 10', 'number'],
834 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
836 ['A list of holds for the stated library to pull for', 'array']
838 method => 'hold_pull_list',
840 __PACKAGE__->register_method(
841 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
845 "Returns the holds for a specific library's pull list.",
846 [ [org_unit => "The library's org id", "number"],
847 [limit => 'An optional page size, defaults to 10', 'number'],
848 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
850 ['A list of holds for the stated library to pull for', 'array']
852 method => 'hold_pull_list',
854 __PACKAGE__->register_method(
855 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
859 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
860 [ [org_unit => "The library's org id", "number"],
861 [limit => 'An optional page size, defaults to 10', 'number'],
862 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
864 ['A list of holds for the stated library to pull for', 'array']
866 method => 'hold_pull_list',
868 __PACKAGE__->register_method(
869 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
873 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
874 [ [org_unit => "The library's org id", "number"],
875 [limit => 'An optional page size, defaults to 10', 'number'],
876 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
878 ['A list of holds for the stated library to pull for', 'array']
880 method => 'hold_pull_list',
883 sub find_optional_surveys {
888 return undef unless ($ou);
889 my $s_table = action::survey->table;
891 my $select = <<" SQL";
894 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
895 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
896 AND s.required IS FALSE;
899 my $sth = action::survey->db_Main->prepare_cached($select);
902 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
906 __PACKAGE__->register_method(
907 api_name => 'open-ils.storage.action.survey.optional',
910 method => 'find_optional_surveys',
913 sub find_required_surveys {
918 return undef unless ($ou);
919 my $s_table = action::survey->table;
921 my $select = <<" SQL";
924 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
925 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
926 AND s.required IS TRUE;
929 my $sth = action::survey->db_Main->prepare_cached($select);
932 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
936 __PACKAGE__->register_method(
937 api_name => 'open-ils.storage.action.survey.required',
940 method => 'find_required_surveys',
943 sub find_usr_summary_surveys {
948 return undef unless ($ou);
949 my $s_table = action::survey->table;
951 my $select = <<" SQL";
954 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
955 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
956 AND s.usr_summary IS TRUE;
959 my $sth = action::survey->db_Main->prepare_cached($select);
962 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
966 __PACKAGE__->register_method(
967 api_name => 'open-ils.storage.action.survey.usr_summary',
970 method => 'find_usr_summary_surveys',
973 sub seconds_to_interval_hash {
974 my $interval = shift;
975 my $limit = shift || 's';
976 $limit =~ s/^(.)/$1/o;
980 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
981 my ($year, $month, $week, $day, $hour, $minute, $second) =
982 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
984 if ($y = int($interval / (60 * 60 * 24 * 365))) {
986 $ym = $interval % (60 * 60 * 24 * 365);
990 return %output if ($limit eq 'y');
992 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
993 $output{$month} = $M;
994 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
998 return %output if ($limit eq 'M');
1000 if ($w = int($Mm / 604800)) {
1001 $output{$week} = $w;
1006 return %output if ($limit eq 'w');
1008 if ($d = int($wm / 86400)) {
1014 return %output if ($limit eq 'd');
1016 if ($h = int($dm / 3600)) {
1017 $output{$hour} = $h;
1022 return %output if ($limit eq 'h');
1024 if ($m = int($hm / 60)) {
1025 $output{$minute} = $m;
1030 return %output if ($limit eq 'm');
1032 if ($s = int($mm)) {
1033 $output{$second} = $s;
1035 $output{$second} = 0 unless (keys %output);
1041 sub generate_fines {
1045 my $overbill = shift;
1047 local $OpenILS::Application::Storage::WRITE = 1;
1052 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
1053 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
1055 push @circs, overdue_circs();
1058 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
1060 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
1061 for my $c (@circs) {
1063 my $ctype = ref($c);
1064 $ctype =~ s/^.+::(\w+)$/$1/;
1066 my $due_date_method = 'due_date';
1067 my $target_copy_method = 'target_copy';
1068 my $circ_lib_method = 'circ_lib';
1069 my $recurring_fine_method = 'recurring_fine';
1070 my $is_reservation = 0;
1071 if ($ctype eq 'reservation') {
1072 $is_reservation = 1;
1073 $due_date_method = 'end_time';
1074 $target_copy_method = 'current_resource';
1075 $circ_lib_method = 'pickup_lib';
1076 $recurring_fine_method = 'fine_amount';
1077 next unless ($c->fine_interval);
1079 #TODO: reservation grace periods
1080 my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
1083 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1084 $log->debug("Cleaning up after previous transaction\n");
1085 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1087 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1089 sprintf("Processing %s %d...",
1090 ($is_reservation ? "reservation" : "circ"), $c->id
1095 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
1097 my $due = $due_dt->epoch;
1100 my $fine_interval = $c->fine_interval;
1101 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
1102 $fine_interval = interval_to_seconds( $fine_interval );
1104 if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
1105 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
1106 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
1110 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
1111 my $tz_offset_s = 0;
1112 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
1113 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
1116 $due -= ($due % $fine_interval) + $tz_offset_s;
1117 $now -= ($now % $fine_interval) + $tz_offset_s;
1121 "ARG! Overdue $ctype ".$c->id.
1122 " for item ".$c->$target_copy_method.
1123 " (user ".$c->usr.").\n".
1124 "\tItem was due on or before: ".localtime($due)."\n");
1126 my @fines = money::billing->search_where(
1129 billing_ts => { '>' => $c->$due_date_method } },
1130 { order_by => 'billing_ts DESC'}
1134 my $fine = $fines[$f_idx] if (@fines);
1136 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
1139 my $current_fine_total = 0;
1140 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
1144 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
1145 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
1147 $log->info( "Potential first billing for circ ".$c->id );
1150 $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});
1153 return if ($last_fine > $now);
1154 # Generate fines for each past interval, including the one we are inside
1155 my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
1157 if ( $last_fine == $due # we have no fines yet
1158 && $grace_period # and we have a grace period
1159 && $now < $due + $grace_period # and some date math says were are within the grace period
1161 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
1162 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
1166 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
1167 return unless ($pending_fine_count);
1169 my $recurring_fine = int($c->$recurring_fine_method * 100);
1170 my $max_fine = int($c->max_fine * 100);
1172 my $skip_closed_check = $U->ou_ancestor_setting_value(
1173 $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.charge_when_closed');
1174 $skip_closed_check = $U->is_true($skip_closed_check);
1176 my $truncate_to_max_fine = $U->ou_ancestor_setting_value(
1177 $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.truncate_to_max_fine');
1178 $truncate_to_max_fine = $U->is_true($truncate_to_max_fine);
1180 my ($latest_billing_ts, $latest_amount) = ('',0);
1181 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
1183 if ($current_fine_total >= $max_fine) {
1184 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
1186 "\tMaximum fine level of ".$c->max_fine.
1187 " reached for this $ctype.\n".
1188 "\tNo more fines will be generated.\n" );
1192 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
1193 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
1194 my $current_bill_count = $bill;
1195 while ( $current_bill_count ) {
1196 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
1197 $current_bill_count--;
1200 my $timestamptz = $billing_ts->strftime('%FT%T%z');
1201 if (!$skip_closed_check) {
1202 my $dow = $billing_ts->day_of_week_0();
1203 my $dow_open = "dow_${dow}_open";
1204 my $dow_close = "dow_${dow}_close";
1206 if (my $h = $hoo{$c->$circ_lib_method}) {
1207 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
1210 my @cl = actor::org_unit::closed_date->search_where(
1211 { close_start => { '<=' => $timestamptz },
1212 close_end => { '>=' => $timestamptz },
1213 org_unit => $c->$circ_lib_method }
1218 # The billing amount for this billing normally ought to be the recurring fine amount.
1219 # However, if the recurring fine amount would cause total fines to exceed the max fine amount,
1220 # we may wish to reduce the amount for this billing (if circ.fines.truncate_to_max_fine is true).
1221 my $this_billing_amount = $recurring_fine;
1222 if ( $truncate_to_max_fine && ($current_fine_total + $this_billing_amount) > $max_fine ) {
1223 $this_billing_amount = ($max_fine - $current_fine_total);
1225 $current_fine_total += $this_billing_amount;
1226 $latest_amount += $this_billing_amount;
1227 $latest_billing_ts = $timestamptz;
1229 money::billing->create(
1230 { xact => ''.$c->id,
1231 note => "System Generated Overdue Fine",
1232 billing_type => "Overdue materials",
1234 amount => sprintf('%0.2f', $this_billing_amount/100),
1235 billing_ts => $timestamptz,
1241 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
1242 if ($latest_billing_ts and $latest_amount);
1244 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1248 # Caluclate penalties inline
1249 OpenILS::Utils::Penalty->calculate_penalties(
1250 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
1254 # Calculate penalties with an aysnc call to the penalty server. This approach
1255 # may lead to duplicate penalties since multiple penalty processes for a
1256 # given user may be running at the same time. Leave this here for reference
1257 # in case we later find that asyc calls are needed in some environments.
1259 'open-ils.penalty.patron_penalty.calculate',
1260 { patronid => ''.$c->usr,
1261 context_org => ''.$c->$circ_lib_method,
1272 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
1273 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
1274 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1275 last if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1279 __PACKAGE__->register_method(
1280 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1283 method => 'generate_fines',
1287 sub MR_records_matching_format {
1293 # include all visible copies, regardless of holdability
1294 my $opac_visible = shift;
1296 # find filters for MR holds
1298 if (defined($filter)) {
1299 ($mr_filter) = @{action::hold_request->db_Main->selectcol_arrayref(
1300 'SELECT metabib.compile_composite_attr(?)',
1306 my $records = [metabib::metarecord->retrieve($MR)->source_records];
1308 my $vis_q = 'asset.record_has_holdable_copy(?,?)';
1309 if ($opac_visible) {
1312 SELECT 1 FROM asset.opac_visible_copies
1313 WHERE record = ? AND circ_lib IN (
1314 SELECT id FROM actor.org_unit_descendants(?)
1320 my $q = "SELECT source FROM metabib.record_attr_vector_list WHERE source = ? AND vlist @@ ? AND $vis_q";
1321 my @args = ( $mr_filter, $org );
1323 $q = "SELECT true WHERE $vis_q";
1327 for my $r ( map { isTrue($_->deleted) ? () : ($_->id) } @$records ) {
1328 # the map{} below is tricky. it puts the record ID in front of each param. see $q above
1329 $client->respond($r)
1330 if @{action::hold_request->db_Main->selectcol_arrayref( $q, {}, map { ( $r => $_ ) } @args )};
1333 return; # discard final l-val
1335 __PACKAGE__->register_method(
1336 api_name => 'open-ils.storage.metarecord.filtered_records',
1340 method => 'MR_records_matching_format',
1344 sub new_hold_copy_targeter {
1347 my $check_expire = shift;
1348 my $one_hold = shift;
1349 my $find_copy = shift;
1351 local $OpenILS::Application::Storage::WRITE = 1;
1353 $self->{target_weight} = {};
1354 $self->{max_loops} = {};
1360 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1361 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
1362 } elsif ( $check_expire ) {
1364 # what's the retarget time threashold?
1366 $check_expire ||= '12h';
1367 $check_expire = interval_to_seconds( $check_expire );
1369 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1372 my $expire_threshold = sprintf(
1373 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1374 $year, $mon, $mday, $hour, $min, $sec
1377 # find all the holds holds needing retargeting
1378 $holds = [ action::hold_request->search_where(
1379 { capture_time => undef,
1380 fulfillment_time => undef,
1381 cancel_time => undef,
1383 prev_check_time => { '<=' => $expire_threshold },
1385 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
1387 # find all the holds holds needing first time targeting
1388 push @$holds, action::hold_request->search(
1389 capture_time => undef,
1390 fulfillment_time => undef,
1391 prev_check_time => undef,
1393 cancel_time => undef,
1394 { order_by => 'selection_depth DESC, request_time' } );
1397 # find all the holds holds needing first time targeting ONLY
1398 $holds = [ action::hold_request->search(
1399 capture_time => undef,
1400 fulfillment_time => undef,
1401 prev_check_time => undef,
1402 cancel_time => undef,
1404 { order_by => 'selection_depth DESC, request_time' } ) ];
1406 } catch Error with {
1408 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1411 my @closed = actor::org_unit::closed_date->search_where(
1412 { close_start => { '<=', 'now' },
1413 close_end => { '>=', 'now' } }
1416 if ($check_expire) {
1418 # $check_expire, if it exists, was already converted to seconds
1419 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1423 my $next_check_time = sprintf(
1424 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1425 $year, $mon, $mday, $hour, $min, $sec
1429 my @closed_at_next = actor::org_unit::closed_date->search_where(
1430 { close_start => { '<=', $next_check_time },
1431 close_end => { '>=', $next_check_time } }
1435 for my $c_at_n (@closed_at_next) {
1436 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1437 push @new_closed, $c_at_n;
1440 @closed = @new_closed;
1444 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1445 my $editor = new_editor;
1447 my $target_when_closed = {};
1448 my $target_when_closed_if_at_pickup_lib = {};
1450 for my $hold (@$holds) {
1452 #start a transaction if needed
1453 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1454 $log->debug("Cleaning up after previous transaction\n");
1455 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1457 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1458 $log->info("Processing hold ".$hold->id."...\n");
1460 #first, re-fetch the hold, to make sure it's not captured already
1461 $hold->remove_from_object_index();
1462 $hold = action::hold_request->retrieve( $hold->id );
1464 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1466 # remove old auto-targeting maps
1467 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1468 $_->delete for (@oldmaps);
1470 if ($hold->expire_time) {
1471 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1472 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1474 # cancel cause = un-targeted expiration
1475 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1477 # refresh fields from the DB while still in the xact
1478 my $fm_hold = $hold->to_fieldmapper;
1480 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1482 # tell A/T the hold was cancelled
1483 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1484 $ses->request('open-ils.trigger.event.autocreate',
1485 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1491 my $all_copies = [];
1493 # find all the potential copies
1494 if ($hold->hold_type eq 'M') {
1496 $self->method_lookup(
1497 'open-ils.storage.metarecord.filtered_records'
1498 )->run( $hold->target, $hold->holdable_formats )
1501 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1502 ->run( $r_id, $hold->selection_ou, $hold->selection_depth );
1504 for my $cn ( @{ $rtree->call_numbers } ) {
1506 asset::copy->search_where(
1507 { id => [map {$_->id} @{ $cn->copies }],
1509 ) if ($cn && @{ $cn->copies });
1512 } elsif ($hold->hold_type eq 'T') {
1514 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1515 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1518 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1522 for my $cn ( @{ $rtree->call_numbers } ) {
1524 asset::copy->search_where(
1525 { id => [map {$_->id} @{ $cn->copies }],
1527 ) if ($cn && @{ $cn->copies });
1529 } elsif ($hold->hold_type eq 'V') {
1531 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1532 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1535 asset::copy->search_where(
1536 { id => [map {$_->id} @{ $vtree->copies }],
1538 ) if ($vtree && @{ $vtree->copies });
1540 } elsif ($hold->hold_type eq 'P') {
1541 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1543 asset::copy->search_where(
1544 { id => [map {$_->target_copy} @part_maps],
1549 } elsif ($hold->hold_type eq 'I') {
1551 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1552 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1555 asset::copy->search_where(
1556 { id => [map {$_->unit->id} @{ $itree->items }],
1558 ) if ($itree && @{ $itree->items });
1560 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1561 my $_cp = asset::copy->retrieve($hold->target);
1562 push @$all_copies, $_cp if $_cp;
1565 # Force and recall holds bypass pretty much everything
1566 if ($hold->hold_type ne 'R' && $hold->hold_type ne 'F') {
1568 @$all_copies = grep { isTrue($_->status->holdable) &&
1569 isTrue($_->location->holdable) &&
1570 isTrue($_->holdable) &&
1571 !isTrue($_->deleted) &&
1572 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1573 ( ( $hold->hold_type ne 'C' && $hold->hold_type ne 'I' # Copy-level holds don't care about parts
1574 && $hold->hold_type ne 'P' ) ? $_->part_maps->count == 0 : 1)
1578 # let 'em know we're still working
1579 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1581 # if we have no copies ...
1582 if (!ref $all_copies || !@$all_copies) {
1583 $log->info("\tNo copies available for targeting at all!\n");
1584 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1586 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1587 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1591 my $copy_count = @$all_copies;
1592 my $found_copy = undef;
1593 $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1595 # map the potentials, so that we can pick up checkins
1596 my $hold_copy_map = {};
1597 $hold_copy_map->{$_->hold}->{$_->target_copy} = $_->proximity
1600 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } )
1604 my $pu_lib = ''.$hold->pickup_lib;
1605 my $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
1606 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1608 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1611 for my $c (@$all_copies) {
1613 next if ($hold->current_copy and $c->id eq $hold->current_copy);
1615 # skip on circ lib is closed IFF we care
1618 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1619 $ignore_closing = ou_ancestor_setting_value_or_cache(
1622 'circ.holds.target_when_closed_if_at_pickup_lib',
1623 $target_when_closed_if_at_pickup_lib
1626 if (not $ignore_closing) { # one more chance to find a reason
1627 # to ignore OU closedness.
1628 $ignore_closing = ou_ancestor_setting_value_or_cache(
1631 'circ.holds.target_when_closed',
1637 # "For hold " . $hold->id . " and copy with circ_lib " .
1638 # $c->circ_lib . " we " .
1639 # ($ignore_closing ? "ignore" : "respect")
1644 (not $ignore_closing) and
1645 (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1648 # target of another hold
1649 next if (action::hold_request
1651 { current_copy => $c->id,
1652 fulfillment_time => undef,
1653 cancel_time => undef,
1658 # we passed all three, keep it
1659 push @good_copies, $c if ($c);
1660 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1663 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1665 my $old_best = $hold->current_copy;
1666 my $old_best_still_valid = 0; # Assume no, but the next line says yes if it is still a potential.
1667 $old_best_still_valid = 1 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies );
1668 $hold->update({ current_copy => undef }) if ($old_best);
1670 if (!scalar(@good_copies)) {
1671 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1672 if ( $old_best_still_valid ) {
1673 # the old copy is still available
1674 $log->debug("\tPushing current_copy back onto the targeting list");
1675 push @good_copies, $old_best;
1677 # oops, old copy is not available
1678 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1679 $hold->update( { prev_check_time => 'today' } );
1680 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1681 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1686 # reset prox list after trimming good copies
1687 $prox_list = create_prox_list(
1689 [ grep { $_->status == 0 || $_->status == 7 } @good_copies ],
1690 $hold, $hold_copy_map
1693 $all_copies = [ grep { ''.$_->circ_lib ne $pu_lib && ( $_->status == 0 || $_->status == 7 ) } @good_copies ];
1695 my $min_prox = [ sort keys %$prox_list ]->[0];
1697 if ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') { # Recall/Force holds bypass hold rules.
1698 $best = $good_copies[0] if(scalar @good_copies);
1700 $best = choose_nearest_copy($hold, { $min_prox => delete($$prox_list{$min_prox}) });
1703 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1706 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1708 $self->{max_loops}{$pu_lib} = $U->ou_ancestor_setting(
1709 $pu_lib, 'circ.holds.max_org_unit_target_loops', $editor
1712 if (defined($self->{max_loops}{$pu_lib})) {
1713 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1715 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1716 my $circ_lib_list = [keys %circ_lib_map];
1718 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1720 # Grab the "biggest" loop for this hold so far
1721 my $current_loop = $cstore->request(
1722 'open-ils.cstore.json_query',
1724 select => { aufhmxl => ['max'] },
1726 where => { hold => $hold->id}
1730 $current_loop = $current_loop->{max} if ($current_loop);
1731 $current_loop ||= 1;
1733 my $exclude_list = $cstore->request(
1734 'open-ils.cstore.json_query.atomic',
1736 select => { aufhol => ['circ_lib'] },
1738 where => { hold => $hold->id}
1743 if ($exclude_list && @$exclude_list) {
1744 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1745 # check to see if we've used up every library in the potentials list
1746 for my $l ( @$circ_lib_list ) {
1748 for my $ex ( @$exclude_list ) {
1754 push(@keepers, $l) if ($keep);
1757 @keepers = @$circ_lib_list;
1760 $current_loop++ if (!@keepers);
1762 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1763 # We haven't exceeded max_loops yet
1765 for my $cp ( @$all_copies ) {
1766 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1769 $all_copies = [@keeper_copies];
1771 # We have, and should remove potentials and cancel the hold
1772 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1773 $_->delete for (@oldmaps);
1775 # cancel cause = un-targeted expiration
1776 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1778 # refresh fields from the DB while still in the xact
1779 my $fm_hold = $hold->to_fieldmapper;
1781 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1783 # tell A/T the hold was cancelled
1784 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1785 $ses->request('open-ils.trigger.event.autocreate',
1786 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1791 $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
1793 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1797 $best = choose_nearest_copy($hold, $prox_list);
1800 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1802 # hold wasn't fulfilled, record the fact
1804 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1805 action::unfulfilled_hold_list->create(
1806 { hold => ''.$hold->id,
1807 current_copy => ''.$old_best->id,
1808 circ_lib => ''.$old_best->circ_lib,
1813 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1814 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1816 $old_best_still_valid &&
1817 !action::hold_request
1819 { current_copy => $old_best->id,
1820 fulfillment_time => undef,
1821 cancel_time => undef,
1824 ( OpenILS::Utils::PermitHold::permit_copy_hold(
1825 { title => $old_best->call_number->record->to_fieldmapper,
1826 patron => $hold->usr->to_fieldmapper,
1827 copy => $old_best->to_fieldmapper,
1828 requestor => $hold->requestor->to_fieldmapper,
1829 request_lib => $hold->request_lib->to_fieldmapper,
1830 pickup_lib => $hold->pickup_lib->id,
1835 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1836 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1838 $hold->update( { prev_check_time => 'now' } );
1839 $log->info( "\tThere were no targetable copies for the hold" );
1840 process_recall($actor, $log, $hold, \@good_copies);
1843 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1844 $log->info("\tProcessing of hold ".$hold->id." complete.");
1847 { hold => $hold->id,
1848 old_target => ($old_best ? $old_best->id : undef),
1849 eligible_copies => $copy_count,
1850 target => ($best ? $best->id : undef),
1851 found_copy => $found_copy };
1856 $log->error("Processing of hold failed: $e");
1857 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1858 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1865 __PACKAGE__->register_method(
1866 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1868 method => 'new_hold_copy_targeter',
1871 sub process_recall {
1872 my ($actor, $log, $hold, $good_copies) = @_;
1874 # Bail early if we don't have required settings to avoid spurious requests
1875 my ($recall_threshold, $return_interval, $fine_rules);
1877 my $rv = $actor->request(
1878 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1882 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1885 $recall_threshold = $rv->{value};
1887 $rv = $actor->request(
1888 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1892 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1895 $return_interval = $rv->{value};
1897 $rv = $actor->request(
1898 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1902 $fine_rules = $rv->{value};
1905 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1907 # We want checked out copies (status = 1) at the hold pickup lib
1908 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1910 my @copy_ids = map { $_->id } @$all_copies;
1912 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1914 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1916 # Iterate over the checked-out copies to find a copy with a
1917 # loan period longer than the recall threshold:
1918 my $circs = [ action::circulation->search_where(
1919 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1920 { order_by => 'due_date ASC' }
1923 # If we have a candidate copy, then:
1924 if (scalar(@$circs)) {
1925 my $circ = $circs->[0];
1926 $log->info("Recalling circ ID : " . $circ->id);
1928 # Give the user a new due date of either a full recall threshold,
1929 # or the return interval, whichever is further in the future
1930 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1931 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1932 $return_date = $threshold_date;
1935 my $update_fields = {
1936 due_date => $return_date,
1937 renewal_remaining => 0,
1940 # If the OU hasn't defined new fine rules for recalls, keep them
1943 $log->info("Apply recall fine rules: $fine_rules");
1944 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1945 $update_fields->{recurring_fine} = $rules->[0];
1946 $update_fields->{fine_interval} = $rules->[1];
1947 $update_fields->{max_fine} = $rules->[2];
1950 # Adjust circ for current user
1951 $circ->update($update_fields);
1953 # Create trigger event for notifying current user
1954 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1955 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1958 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1961 sub reservation_targeter {
1964 my $one_reservation = shift;
1966 local $OpenILS::Application::Storage::WRITE = 1;
1971 if ($one_reservation) {
1972 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1973 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1976 # find all the reservations needing targeting
1978 booking::reservation->search_where(
1979 { current_resource => undef,
1980 cancel_time => undef,
1981 start_time => { '>' => 'now' }
1983 { order_by => 'start_time' }
1987 } catch Error with {
1989 die "Could not retrieve reservation requests:\n\n$e\n";
1993 for my $bresv (@$reservations) {
1995 #start a transaction if needed
1996 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1997 $log->debug("Cleaning up after previous transaction\n");
1998 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
2000 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
2001 $log->info("Processing reservation ".$bresv->id."...\n");
2003 #first, re-fetch the hold, to make sure it's not captured already
2004 $bresv->remove_from_object_index();
2005 $bresv = booking::reservation->retrieve( $bresv->id );
2007 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
2009 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
2010 if (DateTime->compare($end_time, DateTime->now) < 0) {
2012 # cancel cause = un-targeted expiration
2013 $bresv->update( { cancel_time => 'now' } );
2015 # refresh fields from the DB while still in the xact
2016 my $fm_bresv = $bresv->to_fieldmapper;
2018 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2020 # tell A/T the reservation was cancelled
2021 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
2022 $ses->request('open-ils.trigger.event.autocreate',
2023 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
2028 my $possible_resources;
2030 # find all the potential resources
2031 if (!$bresv->target_resource) {
2032 my $filter = { type => $bresv->target_resource_type };
2033 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
2035 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
2037 $filter->{available} = [$bresv->start_time, $bresv->end_time];
2038 my $ses = OpenSRF::AppSession->create('open-ils.booking');
2039 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
2041 $possible_resources = $bresv->target_resource;
2044 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
2045 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
2048 my @good_resources = ();
2050 for my $res (@$all_resources) {
2051 unless (isTrue($res->type->catalog_item)) {
2052 push @good_resources, $res;
2056 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
2059 push @good_resources, $res;
2063 # At this point, if we're just targeting one specific
2064 # resource, just succeed. We don't care about its present
2066 if ($bresv->target_resource) {
2067 push @good_resources, $res;
2071 if ($copy->status->id == 0 || $copy->status->id == 7) {
2072 push @good_resources, $res;
2076 if ($copy->status->id == 1) {
2077 my $circs = [ action::circulation->search_where(
2078 {target_copy => $copy->id, checkin_time => undef },
2079 { order_by => 'id DESC' }
2083 my $due_date = $circs->[0]->due_date;
2084 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
2085 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
2086 if (DateTime->compare($start_time, $due_date) < 0) {
2087 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
2091 push @good_resources, $res;
2097 push @good_resources, $res if (isTrue($copy->status->holdable));
2100 # let 'em know we're still working
2101 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2103 # if we have no copies ...
2104 if (!@good_resources) {
2105 $log->info("\tNo resources available for targeting at all!\n");
2106 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
2109 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2113 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
2115 # LFW: note that after the inclusion of hold proximity
2116 # adjustment, this prox_list is the only prox_list
2117 # array in this perl package. Other occurences are
2123 $_->owner == $bresv->pickup_lib
2127 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
2128 # $all_copies is now a list of copies not at the pickup library
2130 my $best = shift @good_resources;
2131 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2134 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
2138 sort { $a->[0] <=> $b->[0] }
2140 [ actor::org_unit_proximity->search_where(
2141 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
2147 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2149 $best = shift @$prox_list
2153 $bresv->update( { current_resource => ''.$best->id } );
2154 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
2157 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2158 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
2161 { reservation => $bresv->id,
2162 current_resource => ($best ? $best->id : undef) };
2167 $log->error("Processing of bresv failed: $e");
2168 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
2169 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
2176 __PACKAGE__->register_method(
2177 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
2179 method => 'reservation_targeter',
2184 my %cache = (titles => {}, cns => {});
2186 sub copy_hold_capture {
2191 if (!defined($cps)) {
2193 $cps = [ asset::copy->search( id => $hold->target ) ];
2194 } catch Error with {
2196 die "Could not retrieve initial volume list:\n\n$e\n";
2200 my @copies = grep { $_->holdable } @$cps;
2202 for (my $i = 0; $i < @$cps; $i++) {
2203 next unless $$cps[$i];
2205 my $cn = $cache{cns}{$copies[$i]->call_number};
2206 my $rec = $cache{titles}{$cn->record};
2207 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
2208 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
2209 $copies[$i] = undef if (
2211 !$self->{user_filter}->request(
2212 'open-ils.circ.permit_hold',
2213 $hold->to_fieldmapper, do {
2214 my $cp_fm = $copies[$i]->to_fieldmapper;
2215 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
2216 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
2217 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
2220 { title => $rec->to_fieldmapper,
2221 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
2222 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
2225 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
2228 @copies = grep { $_ } @copies;
2230 my $count = @copies;
2232 return unless ($count);
2234 action::hold_copy_map->search( hold => $hold->id )->delete_all;
2237 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
2238 for my $c (@copies) {
2239 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
2241 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
2247 sub choose_nearest_copy {
2249 my $prox_list = shift;
2251 for my $p ( sort keys %$prox_list ) {
2252 next unless (ref $$prox_list{$p});
2254 my @capturable = @{ $$prox_list{$p} };
2255 next unless (@capturable);
2257 my $rand = int(rand(scalar(@capturable)));
2259 while (my ($c) = splice(@capturable, $rand, 1)) {
2260 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
2261 { title => $c->call_number->record->to_fieldmapper,
2262 patron => $hold->usr->to_fieldmapper,
2263 copy => $c->to_fieldmapper,
2264 requestor => $hold->requestor->to_fieldmapper,
2265 request_lib => $hold->request_lib->to_fieldmapper,
2266 pickup_lib => $hold->pickup_lib->id,
2272 last unless(@capturable);
2273 $rand = int(rand(scalar(@capturable)));
2278 sub create_prox_list {
2283 my $hold_copy_map = shift || {};
2286 my $editor = new_editor;
2287 for my $cp (@$copies) {
2288 my $prox = $hold_copy_map->{"$hold"}->{"$cp"}; # Allow CDBI stringification to get the pkey
2289 ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib, $hold ) unless (defined $prox);
2290 next unless (defined($prox));
2292 my $copy_circ_lib = ''.$cp->circ_lib;
2293 # Fetch the weighting value for hold targeting, defaulting to 1
2294 $self->{target_weight}{$copy_circ_lib} ||= $U->ou_ancestor_setting(
2295 $copy_circ_lib.'', 'circ.holds.org_unit_target_weight', $editor
2297 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
2298 $self->{target_weight}{$copy_circ_lib} ||= 1;
2300 $prox_list{$prox} = [] unless defined($prox_list{$prox});
2301 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
2302 push @{$prox_list{$prox}}, $cp;
2308 sub volume_hold_capture {
2313 if (!defined($vols)) {
2315 $vols = [ asset::call_number->search( id => $hold->target ) ];
2316 $cache{cns}{$_->id} = $_ for (@$vols);
2317 } catch Error with {
2319 die "Could not retrieve initial volume list:\n\n$e\n";
2323 my @v_ids = map { $_->id } @$vols;
2327 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
2329 } catch Error with {
2331 warn "Could not retrieve copy list:\n\n$e\n";
2334 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
2337 sub title_hold_capture {
2342 if (!defined($titles)) {
2344 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
2345 $cache{titles}{$_->id} = $_ for (@$titles);
2346 } catch Error with {
2348 die "Could not retrieve initial title list:\n\n$e\n";
2352 my @t_ids = map { $_->id } @$titles;
2355 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
2357 } catch Error with {
2359 warn "Could not retrieve volume list:\n\n$e\n";
2362 $cache{cns}{$_->id} = $_ for (@$cn_list);
2364 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);