1 package OpenILS::Application::Storage::Publisher::action;
2 use parent qw/OpenILS::Application::Storage::Publisher/;
5 use OpenSRF::Utils::Logger qw/:level :logger/;
6 use OpenSRF::Utils qw/:datetime/;
7 use OpenSRF::Utils::JSON;
8 use OpenSRF::AppSession;
9 use OpenSRF::EX qw/:try/;
10 use OpenILS::Utils::Fieldmapper;
11 use OpenILS::Utils::PermitHold;
12 use OpenILS::Utils::CStoreEditor qw/:funcs/;
14 use DateTime::Format::ISO8601;
15 use OpenILS::Utils::Penalty;
17 use OpenILS::Application::Circ::CircCommon;
18 use OpenILS::Application::AppUtils;
19 my $U = "OpenILS::Application::AppUtils";
21 # Used in build_hold_sort_clause(). See the hash %order_by_sprintf_args in
22 # that sub to confirm what gets used to replace the formatters, and see
23 # nearest_hold() for the main body of the SQL query that these go into.
24 my %HOLD_SORT_ORDER_BY = (
26 hprox => 'actor.org_unit_proximity(%d, h.pickup_lib)', # $cp->call_number->owning_lib
27 aprox => 'COALESCE(hm.proximity, p.prox)',
28 approx => 'action.hold_copy_calculated_proximity(h.id, %d, %d)', # $cp,$here
29 priority => 'pgt.hold_priority',
30 cut => 'CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END',
31 depth => 'h.selection_depth',
32 rtime => 'h.request_time',
35 last_event_on_copy.place <> %d AND
36 copy_has_not_been_home.result
37 THEN actor.org_unit_proximity(%d, h.pickup_lib)
40 !, # $cp->call_number->owning_lib x 2
43 last_event_on_copy.place <> %d AND
44 copy_has_not_been_home_even_to_idle.result
45 THEN actor.org_unit_proximity(%d, h.pickup_lib)
48 !, # $cp->call_number->owning_lib x 2
54 return 1 if ($v == 1);
55 return 1 if ($v =~ /^t/io);
56 return 1 if ($v =~ /^y/io);
60 sub ou_ancestor_setting_value_or_cache {
61 # cache should be specific to setting
62 my ($e, $org_id, $setting, $cache) = @_;
64 if (not exists $cache->{$org_id}) {
65 my $r = $U->ou_ancestor_setting(
66 $org_id, $setting, $e # undef $e is ok
70 $cache->{$org_id} = $r->{value};
72 $cache->{$org_id} = undef;
75 return $cache->{$org_id};
78 my $parser = DateTime::Format::ISO8601->new;
79 my $log = 'OpenSRF::Utils::Logger';
81 sub open_noncat_circs {
86 my $a = action::non_cataloged_circulation->table;
87 my $c = config::non_cataloged_type->table;
92 JOIN $c c ON (a.item_type = c.id)
93 WHERE a.circ_time + c.circ_duration > current_timestamp
97 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
99 __PACKAGE__->register_method(
100 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
101 method => 'open_noncat_circs',
107 sub ou_hold_requests {
112 my $h_table = action::hold_request->table;
113 my $c_table = asset::copy->table;
114 my $o_table = actor::org_unit->table;
119 JOIN $c_table cp ON (cp.id = h.current_copy)
120 JOIN $o_table ou ON (ou.id = cp.circ_lib)
122 AND h.capture_time IS NULL
123 AND h.cancel_time IS NULL
124 AND (h.expire_time IS NULL OR h.expire_time > NOW())
125 ORDER BY h.request_time
128 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
131 $client->respond($_) for (
134 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
138 } @{ $sth->fetchall_arrayref }
142 __PACKAGE__->register_method(
143 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
147 method => 'ou_hold_requests',
151 # partition -- if set, an 'undef' will be inserted into the result list
152 # between the last circulation and the first reservation. This is
153 # useful in conjunction with 'idlist' so the caller can tell what type
154 # of transaction the ID refers to without having to query the DB.
156 my $upper_interval = shift || '1 millennium';
158 my $partition = shift;
160 # Only retrieve ID's in the initial query if that's all the caller needs.
161 my $contents = $idlist ? 'id' : '*';
163 my $c_t = action::circulation->table;
168 WHERE stop_fines IS NULL
169 AND due_date < ( CURRENT_TIMESTAMP - grace_period )
170 AND fine_interval < ?::INTERVAL
173 my $sth = action::circulation->db_Main->prepare_cached($sql);
174 $sth->execute($upper_interval);
176 my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
178 push (@circs, undef) if $partition;
180 $c_t = booking::reservation->table;
184 WHERE return_time IS NULL
185 AND end_time < ( CURRENT_TIMESTAMP )
186 AND fine_interval IS NOT NULL
187 AND cancel_time IS NULL
190 $sth = action::circulation->db_Main->prepare_cached($sql);
193 push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
198 sub complete_reshelving {
203 local $OpenILS::Application::Storage::WRITE = 1;
205 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
206 unless (interval_to_seconds( $window ));
208 my $cp = asset::copy->table;
217 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)
220 my $sth = action::circulation->db_Main->prepare_cached($sql);
221 $sth->execute($window);
226 __PACKAGE__->register_method(
227 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
230 method => 'complete_reshelving',
233 sub mark_longoverdue {
238 local $OpenILS::Application::Storage::WRITE = 1;
240 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
241 unless (interval_to_seconds( $window ));
243 my $setting = actor::org_unit_setting->table;
244 my $circ = action::circulation->table;
248 SET stop_fines = 'LONGOVERDUE',
249 stop_fines_time = now()
253 LEFT JOIN $setting setting
254 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
255 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
256 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
260 my $sth = action::circulation->db_Main->prepare_cached($sql);
261 $sth->execute($window);
266 __PACKAGE__->register_method(
267 api_name => 'open-ils.storage.action.circulation.long_overdue',
270 method => 'mark_longoverdue',
273 sub auto_thaw_frozen_holds {
277 local $OpenILS::Application::Storage::WRITE = 1;
279 my $holds = action::hold_request->table;
281 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
283 my $sth = action::hold_request->db_Main->prepare_cached($sql);
289 __PACKAGE__->register_method(
290 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
294 method => 'auto_thaw_frozen_holds',
301 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
303 $client->respond( $idlist ? $_ : $_->to_fieldmapper ) for ( overdue_circs('', $idlist) );
308 __PACKAGE__->register_method(
309 api_name => 'open-ils.storage.action.circulation.overdue',
312 method => 'grab_overdue',
314 Return list of overdue circulations and reservations to be used for fine generation.
315 Despite the name, this is not a generic method for retrieving all overdue loans,
316 as it excludes loans that have already hit the maximum fine limit.
319 __PACKAGE__->register_method(
320 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
323 method => 'grab_overdue',
326 sub get_hold_sort_order {
329 my $dbh = action::hold_request->db_Main;
331 # The purpose of this function is to return column names in a DB-configured
332 # order, so it won't do to add columns here or change column names unless
333 # you also change the expectation of anything calling this function.
335 my $row = $dbh->selectrow_hashref(
338 cbho.pprox, cbho.hprox, cbho.aprox, cbho.approx, cbho.priority,
339 cbho.cut, cbho.depth, cbho.htime, cbho.shtime, cbho.rtime
340 FROM config.best_hold_order cbho
342 SELECT oils_json_to_text(value)::INT
343 FROM actor.org_unit_ancestor_setting('circ.hold_capture_order', ?)
347 pprox => 1, hprox => 8, aprox => 2, priority => 3,
348 cut => 4, depth => 5, htime => 7, rtime => 6
351 # Return only the keys of our hash, sorted by value,
352 # keys for null values omitted.
354 grep { defined $row->{$_} } (
355 sort {$row->{$a} cmp $row->{$b}} keys %$row
360 # Returns an ORDER BY clause
361 # *and* a string with a CTE expression to precede the nearest-hold SQL query
362 # *and* a string with extra JOIN statements needed
363 sub build_hold_sort_clause {
364 my ($columns, $cp, $here) = @_;
366 my %order_by_sprintf_args = (
367 hprox => [$cp->call_number->owning_lib],
368 approx => [$cp->id, $here],
369 htime => [$cp->call_number->owning_lib, $cp->call_number->owning_lib],
370 shtime => [$cp->call_number->owning_lib, $cp->call_number->owning_lib]
375 foreach my $col (@$columns) {
376 if ($col eq 'htime' and not $ctes_needed) {
378 } elsif ($col eq 'shtime') {
383 @args = @{$order_by_sprintf_args{$col}} if
384 exists $order_by_sprintf_args{$col};
386 push @clauses, sprintf($HOLD_SORT_ORDER_BY{$col}, @args);
388 last if $col eq 'rtime'; # rtime is effectively unique, no need for
389 # more order-by clauses after that.
392 my ($ctes, $joins) = ("", "");
393 if ($ctes_needed >= 1) {
394 # Each CTE serves the next. The first is one version or another
395 # of last_event_on_copy, which is described in holds-go-home.txt
396 # TechRef, but it essentially returns place and time of the most
397 # recent transit or circ to do with a copy, and failing that it
398 # returns a synthetic event that means "here" and "now".
400 if ($ctes_needed == 2) {
402 , last_event_on_copy AS ( -- combined circ and transit version
408 COALESCE(dest_recv_time, source_send_time) AS moment
409 FROM action.transit_copy
410 WHERE target_copy = %d
411 ORDER BY moment DESC LIMIT 1
415 COALESCE(checkin_lib, circ_lib) AS place,
416 COALESCE(checkin_time, xact_start) AS moment
417 FROM action.circulation
418 WHERE target_copy = %d
419 ORDER BY moment DESC LIMIT 1
425 ) x ORDER BY concrete DESC, moment DESC LIMIT 1
426 ) !, $cp->id, $cp->id, $cp->call_number->owning_lib);
429 , last_event_on_copy AS ( -- circ only version
433 COALESCE(checkin_lib, circ_lib) AS place,
434 COALESCE(checkin_time, xact_start) AS moment
435 FROM action.circulation
436 WHERE target_copy = %d
437 ORDER BY moment DESC LIMIT 1
442 ) x ORDER BY concrete DESC, moment DESC LIMIT 1
443 ) !, $cp->id, $cp->call_number->owning_lib);
447 JOIN last_event_on_copy ON (true)
450 # For our next auxiliary query, the question we seek to answer is,
451 # "has our copy been circulating away from home too long?"
453 # Have there been no checkouts at the copy's circ_lib since the
454 # beginning of our go-home interval?
456 # [We use sprintf because the outer function that's going to send one
457 # big query through DBI is blind to our process of dynamically building
458 # these CTEs, and it wouldn't know what bind parameters to pass unless
459 # we did a lot more work here. This is injection-safe because we only
460 # use the %d formatter.]
462 , copy_has_not_been_home AS (
465 SELECT MIN(circ.id) FROM action.circulation circ
466 JOIN go_home_interval ON (true)
468 circ.target_copy = %d AND
469 circ.circ_lib = %d AND
470 circ.xact_start >= NOW() - go_home_interval.value
472 ) !, $cp->id, $cp->circ_lib);
475 JOIN copy_has_not_been_home ON (true)
479 if ($ctes_needed == 2) {
480 # By this query, we mean to determine that the copy hasn't landed at
481 # home by means of transit during the go-home interval (in addition
482 # to not having circulated from home in the same time frame).
484 # There have been no homebound transits that arrived for this copy
485 # since the beginning of the go-home interval.
488 , copy_has_not_been_home_even_to_idle AS (
489 SELECT result AND NOT (
490 SELECT COUNT(*)::INT::BOOL
491 FROM action.transit_copy atc
493 atc.target_copy = %d AND
494 (atc.dest = %d OR atc.source = %d) AND
495 atc.dest_recv_time >= NOW() - (SELECT value FROM go_home_interval)
496 ) AS result FROM copy_has_not_been_home
497 ) !, $cp->id, $cp->circ_lib, $cp->circ_lib);
498 $joins .= " JOIN copy_has_not_been_home_even_to_idle ON (true) ";
502 join(", ", @clauses),
511 my $here = shift; # just the ID
512 my $cp = shift; # now an object with call_number fleshed,
513 # formerly just copy ID
514 my $limit = int(shift()) || 10;
515 my $age = shift() || '0 seconds';
518 $log->info("deprecated 'fifo' param true, but ignored") if isTrue($fifo);
520 # ScriptBuilder fleshes the circ_lib, which confuses things; ensure we
521 # are working with a circ lib ID and not an object
523 if (ref $cp->circ_lib) {
524 $cp_circ_lib = $cp->circ_lib->id;
526 $cp_circ_lib = $cp->circ_lib;
530 if (ref $cp->call_number->owning_lib) {
531 $cp_owning_lib = $cp->call_number->owning_lib->id;
533 $cp_owning_lib = $cp->call_number->owning_lib;
536 my ($holdsort, $addl_cte, $addl_join) =
537 build_hold_sort_clause(get_hold_sort_order($cp_owning_lib), $cp, $here);
539 local $OpenILS::Application::Storage::WRITE = 1;
541 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $cp_circ_lib, $here, $cp->id, $age);
542 WITH go_home_interval AS (
543 SELECT OILS_JSON_TO_TEXT(
544 (SELECT value FROM actor.org_unit_ancestor_setting(
545 'circ.hold_go_home_interval', ?
547 ))::INTERVAL AS value
551 FROM action.hold_request h
552 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
553 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
554 JOIN actor.usr au ON (au.id = h.usr)
555 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
556 LEFT JOIN actor.usr_standing_penalty ausp
557 ON ( au.id = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
558 LEFT JOIN config.standing_penalty csp
559 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
561 WHERE hm.target_copy = ?
562 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR hm.proximity = 0 OR p.prox = 0)
563 AND h.capture_time IS NULL
564 AND h.cancel_time IS NULL
565 AND (h.expire_time IS NULL OR h.expire_time > NOW())
566 AND h.frozen IS FALSE
568 ORDER BY CASE WHEN h.hold_type IN ('R','F') THEN 0 ELSE 1 END, $holdsort
572 $client->respond( $_ ) for ( @$ids );
575 __PACKAGE__->register_method(
576 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
579 method => 'nearest_hold',
582 sub targetable_holds {
585 my $check_expire = shift;
587 $check_expire ||= '12h';
589 local $OpenILS::Application::Storage::WRITE = 1;
591 # json_query can *almost* represent this query, but can't
592 # handle the CASE statement or the interval arithmetic
593 my $query = <<" SQL";
594 SELECT ahr.id, mmsm.metarecord
595 FROM action.hold_request ahr
596 JOIN reporter.hold_request_record USING (id)
597 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
598 WHERE capture_time IS NULL
599 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
600 AND fulfillment_time IS NULL
601 AND cancel_time IS NULL
603 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
605 my $sth = action::hold_request->db_Main->prepare_cached($query);
606 $sth->execute($check_expire);
607 $client->respond( $_ ) for @{ $sth->fetchall_arrayref };
612 __PACKAGE__->register_method(
613 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
616 method => 'targetable_holds',
618 Returns ordered list of hold request and metarecord IDs
619 for all hold requests that are available for initial targeting
621 @param check interval
622 @return list of pairs of hold request and metarecord IDs
626 sub next_resp_group_id {
630 # XXX This is not replication safe!!!
632 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
633 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
637 __PACKAGE__->register_method(
638 api_name => 'open-ils.storage.action.survey_response.next_group_id',
640 method => 'next_resp_group_id',
643 sub patron_circ_summary {
648 return undef unless ($id);
649 my $c_table = action::circulation->table;
650 my $b_table = money::billing->table;
652 $log->debug("Retrieving patron summary for id $id", DEBUG);
654 my $select = <<" SQL";
655 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
657 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
659 AND c.xact_finish IS NULL
661 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
662 OR c.stop_fines IS NULL
666 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
668 __PACKAGE__->register_method(
669 api_name => 'open-ils.storage.action.circulation.patron_summary',
671 method => 'patron_circ_summary',
674 #XXX Fix stored proc calls
675 sub find_local_surveys {
680 return undef unless ($ou);
681 my $s_table = action::survey->table;
683 my $select = <<" SQL";
686 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
687 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
690 my $sth = action::survey->db_Main->prepare_cached($select);
693 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
697 __PACKAGE__->register_method(
698 api_name => 'open-ils.storage.action.survey.all',
701 method => 'find_local_surveys',
704 #XXX Fix stored proc calls
705 sub find_opac_surveys {
710 return undef unless ($ou);
711 my $s_table = action::survey->table;
713 my $select = <<" SQL";
716 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
717 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
721 my $sth = action::survey->db_Main->prepare_cached($select);
724 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
728 __PACKAGE__->register_method(
729 api_name => 'open-ils.storage.action.survey.opac',
732 method => 'find_opac_surveys',
739 my $limit = shift || 10;
740 my $offset = shift || 0;
742 return undef unless ($ou);
743 my $h_table = action::hold_request->table;
744 my $a_table = asset::copy->table;
745 my $ord_table = asset::copy_location_order->table;
747 my $idlist = 1 if ($self->api_name =~/id_list/o);
748 my $count = 1 if ($self->api_name =~/count$/o);
750 my $status_filter = '';
751 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
753 my $select = <<" SQL";
756 JOIN $a_table a ON (h.current_copy = a.id)
757 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
759 AND h.capture_time IS NULL
760 AND h.cancel_time IS NULL
761 AND (h.expire_time IS NULL OR h.expire_time > NOW())
764 FROM actor.usr_standing_penalty ausp
765 JOIN config.standing_penalty csp ON (
766 csp.id = ausp.standing_penalty
767 AND csp.block_list LIKE '%CAPTURE%'
769 WHERE h.usr = ausp.usr
770 AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() )
773 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
780 SELECT count(DISTINCT h.id)
782 JOIN $a_table a ON (h.current_copy = a.id)
784 AND h.capture_time IS NULL
785 AND h.cancel_time IS NULL
786 AND (h.expire_time IS NULL OR h.expire_time > NOW())
789 FROM actor.usr_standing_penalty ausp
790 JOIN config.standing_penalty csp ON (
791 csp.id = ausp.standing_penalty
792 AND csp.block_list LIKE '%CAPTURE%'
794 WHERE h.usr = ausp.usr
795 AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() )
801 my $sth = action::survey->db_Main->prepare_cached($select);
805 $client->respond( $sth->fetchall_arrayref()->[0][0] );
807 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
809 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
814 __PACKAGE__->register_method(
815 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
819 "Returns a count of holds for a specific library's pull list.",
820 [ [org_unit => "The library's org id", "number"] ],
821 ['A count of holds for the stated library to pull ', 'number']
823 method => 'hold_pull_list',
825 __PACKAGE__->register_method(
826 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
830 "Returns a status filtered count of holds for a specific library's pull list.",
831 [ [org_unit => "The library's org id", "number"] ],
832 ['A status filtered count of holds for the stated library to pull ', 'number']
834 method => 'hold_pull_list',
836 __PACKAGE__->register_method(
837 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
841 "Returns the hold ids for a specific library's pull list.",
842 [ [org_unit => "The library's org id", "number"],
843 [limit => 'An optional page size, defaults to 10', 'number'],
844 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
846 ['A list of holds for the stated library to pull for', 'array']
848 method => 'hold_pull_list',
850 __PACKAGE__->register_method(
851 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
855 "Returns the holds for a specific library's pull list.",
856 [ [org_unit => "The library's org id", "number"],
857 [limit => 'An optional page size, defaults to 10', 'number'],
858 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
860 ['A list of holds for the stated library to pull for', 'array']
862 method => 'hold_pull_list',
864 __PACKAGE__->register_method(
865 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
869 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
870 [ [org_unit => "The library's org id", "number"],
871 [limit => 'An optional page size, defaults to 10', 'number'],
872 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
874 ['A list of holds for the stated library to pull for', 'array']
876 method => 'hold_pull_list',
878 __PACKAGE__->register_method(
879 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
883 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
884 [ [org_unit => "The library's org id", "number"],
885 [limit => 'An optional page size, defaults to 10', 'number'],
886 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
888 ['A list of holds for the stated library to pull for', 'array']
890 method => 'hold_pull_list',
893 sub find_optional_surveys {
898 return undef unless ($ou);
899 my $s_table = action::survey->table;
901 my $select = <<" SQL";
904 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
905 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
906 AND s.required IS FALSE;
909 my $sth = action::survey->db_Main->prepare_cached($select);
912 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
916 __PACKAGE__->register_method(
917 api_name => 'open-ils.storage.action.survey.optional',
920 method => 'find_optional_surveys',
923 sub find_required_surveys {
928 return undef unless ($ou);
929 my $s_table = action::survey->table;
931 my $select = <<" SQL";
934 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
935 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
936 AND s.required IS TRUE;
939 my $sth = action::survey->db_Main->prepare_cached($select);
942 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
946 __PACKAGE__->register_method(
947 api_name => 'open-ils.storage.action.survey.required',
950 method => 'find_required_surveys',
953 sub find_usr_summary_surveys {
958 return undef unless ($ou);
959 my $s_table = action::survey->table;
961 my $select = <<" SQL";
964 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
965 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
966 AND s.usr_summary IS TRUE;
969 my $sth = action::survey->db_Main->prepare_cached($select);
972 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
976 __PACKAGE__->register_method(
977 api_name => 'open-ils.storage.action.survey.usr_summary',
980 method => 'find_usr_summary_surveys',
983 sub seconds_to_interval_hash {
984 my $interval = shift;
985 my $limit = shift || 's';
986 $limit =~ s/^(.)/$1/o;
990 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
991 my ($year, $month, $week, $day, $hour, $minute, $second) =
992 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
994 if ($y = int($interval / (60 * 60 * 24 * 365))) {
996 $ym = $interval % (60 * 60 * 24 * 365);
1000 return %output if ($limit eq 'y');
1002 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
1003 $output{$month} = $M;
1004 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
1008 return %output if ($limit eq 'M');
1010 if ($w = int($Mm / 604800)) {
1011 $output{$week} = $w;
1016 return %output if ($limit eq 'w');
1018 if ($d = int($wm / 86400)) {
1024 return %output if ($limit eq 'd');
1026 if ($h = int($dm / 3600)) {
1027 $output{$hour} = $h;
1032 return %output if ($limit eq 'h');
1034 if ($m = int($hm / 60)) {
1035 $output{$minute} = $m;
1040 return %output if ($limit eq 'm');
1042 if ($s = int($mm)) {
1043 $output{$second} = $s;
1045 $output{$second} = 0 unless (keys %output);
1051 sub generate_fines {
1055 my $overbill = shift;
1057 local $OpenILS::Application::Storage::WRITE = 1;
1062 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
1063 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
1065 push @circs, overdue_circs(undef, 1, 1);
1068 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
1070 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
1071 my $handling_resvs = 0;
1072 for my $c (@circs) {
1074 my $ctype = ref($c);
1076 if (!$ctype) { # fetched via idlist
1077 if ($handling_resvs) {
1078 $c = booking::reservation->retrieve($c);
1079 } elsif (not defined $c) {
1080 # an undef value is the indicator that we are moving
1081 # from processing circulations to reservations.
1082 $handling_resvs = 1;
1085 $c = action::circulation->retrieve($c);
1090 $ctype =~ s/^.+::(\w+)$/$1/;
1092 my $due_date_method = 'due_date';
1093 my $target_copy_method = 'target_copy';
1094 my $circ_lib_method = 'circ_lib';
1095 my $recurring_fine_method = 'recurring_fine';
1096 my $is_reservation = 0;
1097 if ($ctype eq 'reservation') {
1098 $is_reservation = 1;
1099 $due_date_method = 'end_time';
1100 $target_copy_method = 'current_resource';
1101 $circ_lib_method = 'pickup_lib';
1102 $recurring_fine_method = 'fine_amount';
1103 next unless ($c->fine_interval);
1105 #TODO: reservation grace periods
1106 my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
1109 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1110 $log->debug("Cleaning up after previous transaction\n");
1111 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1113 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1115 sprintf("Processing %s %d...",
1116 ($is_reservation ? "reservation" : "circ"), $c->id
1121 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
1123 my $due = $due_dt->epoch;
1126 my $fine_interval = $c->fine_interval;
1127 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
1128 $fine_interval = interval_to_seconds( $fine_interval );
1130 if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
1131 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
1132 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
1136 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
1137 my $tz_offset_s = 0;
1138 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
1139 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
1142 $due -= ($due % $fine_interval) + $tz_offset_s;
1143 $now -= ($now % $fine_interval) + $tz_offset_s;
1147 "ARG! Overdue $ctype ".$c->id.
1148 " for item ".$c->$target_copy_method.
1149 " (user ".$c->usr.").\n".
1150 "\tItem was due on or before: ".localtime($due)."\n");
1152 my @fines = money::billing->search_where(
1155 billing_ts => { '>' => $c->$due_date_method } },
1156 { order_by => 'billing_ts DESC'}
1160 my $fine = $fines[$f_idx] if (@fines);
1162 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
1165 my $current_fine_total = 0;
1166 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
1170 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
1171 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
1173 $log->info( "Potential first billing for circ ".$c->id );
1176 $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});
1179 return if ($last_fine > $now);
1180 # Generate fines for each past interval, including the one we are inside
1181 my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
1183 if ( $last_fine == $due # we have no fines yet
1184 && $grace_period # and we have a grace period
1185 && $now < $due + $grace_period # and some date math says were are within the grace period
1187 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
1188 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
1192 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
1193 return unless ($pending_fine_count);
1195 my $recurring_fine = int($c->$recurring_fine_method * 100);
1196 my $max_fine = int($c->max_fine * 100);
1198 my $skip_closed_check = $U->ou_ancestor_setting_value(
1199 $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.charge_when_closed');
1200 $skip_closed_check = $U->is_true($skip_closed_check);
1202 my $truncate_to_max_fine = $U->ou_ancestor_setting_value(
1203 $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.truncate_to_max_fine');
1204 $truncate_to_max_fine = $U->is_true($truncate_to_max_fine);
1206 my ($latest_billing_ts, $latest_amount) = ('',0);
1207 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
1209 if ($current_fine_total >= $max_fine) {
1210 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
1212 "\tMaximum fine level of ".$c->max_fine.
1213 " reached for this $ctype.\n".
1214 "\tNo more fines will be generated.\n" );
1218 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
1219 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
1220 my $current_bill_count = $bill;
1221 while ( $current_bill_count ) {
1222 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
1223 $current_bill_count--;
1226 my $timestamptz = $billing_ts->strftime('%FT%T%z');
1227 if (!$skip_closed_check) {
1228 my $dow = $billing_ts->day_of_week_0();
1229 my $dow_open = "dow_${dow}_open";
1230 my $dow_close = "dow_${dow}_close";
1232 if (my $h = $hoo{$c->$circ_lib_method}) {
1233 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
1236 my @cl = actor::org_unit::closed_date->search_where(
1237 { close_start => { '<=' => $timestamptz },
1238 close_end => { '>=' => $timestamptz },
1239 org_unit => $c->$circ_lib_method }
1244 # The billing amount for this billing normally ought to be the recurring fine amount.
1245 # However, if the recurring fine amount would cause total fines to exceed the max fine amount,
1246 # we may wish to reduce the amount for this billing (if circ.fines.truncate_to_max_fine is true).
1247 my $this_billing_amount = $recurring_fine;
1248 if ( $truncate_to_max_fine && ($current_fine_total + $this_billing_amount) > $max_fine ) {
1249 $this_billing_amount = ($max_fine - $current_fine_total);
1251 $current_fine_total += $this_billing_amount;
1252 $latest_amount += $this_billing_amount;
1253 $latest_billing_ts = $timestamptz;
1255 money::billing->create(
1256 { xact => ''.$c->id,
1257 note => "System Generated Overdue Fine",
1258 billing_type => "Overdue materials",
1260 amount => sprintf('%0.2f', $this_billing_amount/100),
1261 billing_ts => $timestamptz,
1267 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
1268 if ($latest_billing_ts and $latest_amount);
1270 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1274 # Caluclate penalties inline
1275 OpenILS::Utils::Penalty->calculate_penalties(
1276 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
1280 # Calculate penalties with an aysnc call to the penalty server. This approach
1281 # may lead to duplicate penalties since multiple penalty processes for a
1282 # given user may be running at the same time. Leave this here for reference
1283 # in case we later find that asyc calls are needed in some environments.
1285 'open-ils.penalty.patron_penalty.calculate',
1286 { patronid => ''.$c->usr,
1287 context_org => ''.$c->$circ_lib_method,
1298 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
1299 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
1300 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1301 last if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1305 __PACKAGE__->register_method(
1306 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1309 method => 'generate_fines',
1313 sub MR_records_matching_format {
1319 # include all visible copies, regardless of holdability
1320 my $opac_visible = shift;
1322 # find filters for MR holds
1324 if (defined($filter)) {
1325 ($mr_filter) = @{action::hold_request->db_Main->selectcol_arrayref(
1326 'SELECT metabib.compile_composite_attr(?)',
1332 my $records = [metabib::metarecord->retrieve($MR)->source_records];
1334 my $vis_q = 'asset.record_has_holdable_copy(?,?)';
1335 if ($opac_visible) {
1338 SELECT 1 FROM asset.opac_visible_copies
1339 WHERE record = ? AND circ_lib IN (
1340 SELECT id FROM actor.org_unit_descendants(?)
1346 my $q = "SELECT source FROM metabib.record_attr_vector_list WHERE source = ? AND vlist @@ ? AND $vis_q";
1347 my @args = ( $mr_filter, $org );
1349 $q = "SELECT true WHERE $vis_q";
1353 for my $r ( map { isTrue($_->deleted) ? () : ($_->id) } @$records ) {
1354 # the map{} below is tricky. it puts the record ID in front of each param. see $q above
1355 $client->respond($r)
1356 if @{action::hold_request->db_Main->selectcol_arrayref( $q, {}, map { ( $r => $_ ) } @args )};
1359 return; # discard final l-val
1361 __PACKAGE__->register_method(
1362 api_name => 'open-ils.storage.metarecord.filtered_records',
1366 method => 'MR_records_matching_format',
1370 sub new_hold_copy_targeter {
1373 my $check_expire = shift;
1374 my $one_hold = shift;
1375 my $find_copy = shift;
1377 local $OpenILS::Application::Storage::WRITE = 1;
1379 $self->{target_weight} = {};
1380 $self->{max_loops} = {};
1386 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1387 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
1388 } elsif ( $check_expire ) {
1390 # what's the retarget time threashold?
1392 $check_expire ||= '12h';
1393 $check_expire = interval_to_seconds( $check_expire );
1395 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1398 my $expire_threshold = sprintf(
1399 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1400 $year, $mon, $mday, $hour, $min, $sec
1403 # find all the holds holds needing retargeting
1404 $holds = [ action::hold_request->search_where(
1405 { capture_time => undef,
1406 fulfillment_time => undef,
1407 cancel_time => undef,
1409 prev_check_time => { '<=' => $expire_threshold },
1411 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
1413 # find all the holds holds needing first time targeting
1414 push @$holds, action::hold_request->search(
1415 capture_time => undef,
1416 fulfillment_time => undef,
1417 prev_check_time => undef,
1419 cancel_time => undef,
1420 { order_by => 'selection_depth DESC, request_time' } );
1423 # find all the holds holds needing first time targeting ONLY
1424 $holds = [ action::hold_request->search(
1425 capture_time => undef,
1426 fulfillment_time => undef,
1427 prev_check_time => undef,
1428 cancel_time => undef,
1430 { order_by => 'selection_depth DESC, request_time' } ) ];
1432 } catch Error with {
1434 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1437 my @closed = actor::org_unit::closed_date->search_where(
1438 { close_start => { '<=', 'now' },
1439 close_end => { '>=', 'now' } }
1442 if ($check_expire) {
1444 # $check_expire, if it exists, was already converted to seconds
1445 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1449 my $next_check_time = sprintf(
1450 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1451 $year, $mon, $mday, $hour, $min, $sec
1455 my @closed_at_next = actor::org_unit::closed_date->search_where(
1456 { close_start => { '<=', $next_check_time },
1457 close_end => { '>=', $next_check_time } }
1461 for my $c_at_n (@closed_at_next) {
1462 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1463 push @new_closed, $c_at_n;
1466 @closed = @new_closed;
1470 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1471 my $editor = new_editor;
1473 my $target_when_closed = {};
1474 my $target_when_closed_if_at_pickup_lib = {};
1476 for my $hold (@$holds) {
1478 #start a transaction if needed
1479 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1480 $log->debug("Cleaning up after previous transaction\n");
1481 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1483 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1484 $log->info("Processing hold ".$hold->id."...\n");
1486 #first, re-fetch the hold, to make sure it's not captured already
1487 $hold->remove_from_object_index();
1488 $hold = action::hold_request->retrieve( $hold->id );
1490 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1492 # remove old auto-targeting maps
1493 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1494 $_->delete for (@oldmaps);
1496 if ($hold->expire_time) {
1497 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1498 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1500 # cancel cause = un-targeted expiration
1501 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1503 # refresh fields from the DB while still in the xact
1504 my $fm_hold = $hold->to_fieldmapper;
1506 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1508 # tell A/T the hold was cancelled
1509 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1510 $ses->request('open-ils.trigger.event.autocreate',
1511 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1517 my $all_copies = [];
1519 # find all the potential copies
1520 if ($hold->hold_type eq 'M') {
1522 $self->method_lookup(
1523 'open-ils.storage.metarecord.filtered_records'
1524 )->run( $hold->target, $hold->holdable_formats )
1527 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1528 ->run( $r_id, $hold->selection_ou, $hold->selection_depth );
1530 for my $cn ( @{ $rtree->call_numbers } ) {
1532 asset::copy->search_where(
1533 { id => [map {$_->id} @{ $cn->copies }],
1535 ) if ($cn && @{ $cn->copies });
1538 } elsif ($hold->hold_type eq 'T') {
1540 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1541 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1544 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1548 for my $cn ( @{ $rtree->call_numbers } ) {
1550 asset::copy->search_where(
1551 { id => [map {$_->id} @{ $cn->copies }],
1553 ) if ($cn && @{ $cn->copies });
1555 } elsif ($hold->hold_type eq 'V') {
1557 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1558 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1561 asset::copy->search_where(
1562 { id => [map {$_->id} @{ $vtree->copies }],
1564 ) if ($vtree && @{ $vtree->copies });
1566 } elsif ($hold->hold_type eq 'P') {
1567 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1569 asset::copy->search_where(
1570 { id => [map {$_->target_copy} @part_maps],
1575 } elsif ($hold->hold_type eq 'I') {
1577 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1578 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1581 asset::copy->search_where(
1582 { id => [map {$_->unit->id} @{ $itree->items }],
1584 ) if ($itree && @{ $itree->items });
1586 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1587 my $_cp = asset::copy->retrieve($hold->target);
1588 push @$all_copies, $_cp if $_cp;
1591 # Force and recall holds bypass pretty much everything
1592 if ($hold->hold_type ne 'R' && $hold->hold_type ne 'F') {
1594 @$all_copies = grep { isTrue($_->status->holdable) &&
1595 isTrue($_->location->holdable) &&
1596 isTrue($_->holdable) &&
1597 !isTrue($_->deleted) &&
1598 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1599 ( ( $hold->hold_type ne 'C' && $hold->hold_type ne 'I' # Copy-level holds don't care about parts
1600 && $hold->hold_type ne 'P' ) ? $_->part_maps->count == 0 : 1)
1604 # let 'em know we're still working
1605 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1607 # if we have no copies ...
1608 if (!ref $all_copies || !@$all_copies) {
1609 $log->info("\tNo copies available for targeting at all!\n");
1610 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1612 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1613 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1617 my $copy_count = @$all_copies;
1618 my $found_copy = undef;
1619 $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1621 # map the potentials, so that we can pick up checkins
1622 my $hold_copy_map = {};
1623 $hold_copy_map->{$_->hold}->{$_->target_copy} = $_->proximity
1626 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } )
1630 my $pu_lib = ''.$hold->pickup_lib;
1631 my $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
1632 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1634 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1637 for my $c (@$all_copies) {
1639 next if ($hold->current_copy and $c->id eq $hold->current_copy);
1641 # skip on circ lib is closed IFF we care
1644 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1645 $ignore_closing = ou_ancestor_setting_value_or_cache(
1648 'circ.holds.target_when_closed_if_at_pickup_lib',
1649 $target_when_closed_if_at_pickup_lib
1652 if (not $ignore_closing) { # one more chance to find a reason
1653 # to ignore OU closedness.
1654 $ignore_closing = ou_ancestor_setting_value_or_cache(
1657 'circ.holds.target_when_closed',
1663 # "For hold " . $hold->id . " and copy with circ_lib " .
1664 # $c->circ_lib . " we " .
1665 # ($ignore_closing ? "ignore" : "respect")
1670 (not $ignore_closing) and
1671 (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1674 # target of another hold
1675 next if (action::hold_request
1677 { current_copy => $c->id,
1678 fulfillment_time => undef,
1679 cancel_time => undef,
1684 # we passed all three, keep it
1685 push @good_copies, $c if ($c);
1686 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1689 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1691 my $old_best = $hold->current_copy;
1692 my $old_best_still_valid = 0; # Assume no, but the next line says yes if it is still a potential.
1693 $old_best_still_valid = 1 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies );
1694 $hold->update({ current_copy => undef }) if ($old_best);
1696 if (!scalar(@good_copies)) {
1697 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1698 if ( $old_best_still_valid ) {
1699 # the old copy is still available
1700 $log->debug("\tPushing current_copy back onto the targeting list");
1701 push @good_copies, $old_best;
1703 # oops, old copy is not available
1704 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1705 $hold->update( { prev_check_time => 'today' } );
1706 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1707 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1712 # reset prox list after trimming good copies
1713 $prox_list = create_prox_list(
1715 [ grep { $_->status == 0 || $_->status == 7 } @good_copies ],
1716 $hold, $hold_copy_map
1719 $all_copies = [ grep { ''.$_->circ_lib ne $pu_lib && ( $_->status == 0 || $_->status == 7 ) } @good_copies ];
1721 my $min_prox = [ sort keys %$prox_list ]->[0];
1723 if ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') { # Recall/Force holds bypass hold rules.
1724 $best = $good_copies[0] if(scalar @good_copies);
1726 $best = choose_nearest_copy($hold, { $min_prox => delete($$prox_list{$min_prox}) });
1729 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1732 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1734 $self->{max_loops}{$pu_lib} = $U->ou_ancestor_setting(
1735 $pu_lib, 'circ.holds.max_org_unit_target_loops', $editor
1738 if (defined($self->{max_loops}{$pu_lib})) {
1739 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1741 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1742 my $circ_lib_list = [keys %circ_lib_map];
1744 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1746 # Grab the "biggest" loop for this hold so far
1747 my $current_loop = $cstore->request(
1748 'open-ils.cstore.json_query',
1750 select => { aufhmxl => ['max'] },
1752 where => { hold => $hold->id}
1756 $current_loop = $current_loop->{max} if ($current_loop);
1757 $current_loop ||= 1;
1759 my $exclude_list = $cstore->request(
1760 'open-ils.cstore.json_query.atomic',
1762 select => { aufhol => ['circ_lib'] },
1764 where => { hold => $hold->id}
1769 if ($exclude_list && @$exclude_list) {
1770 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1771 # check to see if we've used up every library in the potentials list
1772 for my $l ( @$circ_lib_list ) {
1774 for my $ex ( @$exclude_list ) {
1780 push(@keepers, $l) if ($keep);
1783 @keepers = @$circ_lib_list;
1786 $current_loop++ if (!@keepers);
1788 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1789 # We haven't exceeded max_loops yet
1791 for my $cp ( @$all_copies ) {
1792 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1795 $all_copies = [@keeper_copies];
1797 # We have, and should remove potentials and cancel the hold
1798 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1799 $_->delete for (@oldmaps);
1801 # cancel cause = un-targeted expiration
1802 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1804 # refresh fields from the DB while still in the xact
1805 my $fm_hold = $hold->to_fieldmapper;
1807 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1809 # tell A/T the hold was cancelled
1810 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1811 $ses->request('open-ils.trigger.event.autocreate',
1812 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1817 $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold, $hold_copy_map );
1819 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1823 $best = choose_nearest_copy($hold, $prox_list);
1826 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1828 # hold wasn't fulfilled, record the fact
1830 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1831 action::unfulfilled_hold_list->create(
1832 { hold => ''.$hold->id,
1833 current_copy => ''.$old_best->id,
1834 circ_lib => ''.$old_best->circ_lib,
1839 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1840 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1842 $old_best_still_valid &&
1843 !action::hold_request
1845 { current_copy => $old_best->id,
1846 fulfillment_time => undef,
1847 cancel_time => undef,
1850 ( OpenILS::Utils::PermitHold::permit_copy_hold(
1851 { title => $old_best->call_number->record->to_fieldmapper,
1852 patron => $hold->usr->to_fieldmapper,
1853 copy => $old_best->to_fieldmapper,
1854 requestor => $hold->requestor->to_fieldmapper,
1855 request_lib => $hold->request_lib->to_fieldmapper,
1856 pickup_lib => $hold->pickup_lib->id,
1861 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1862 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1864 $hold->update( { prev_check_time => 'now' } );
1865 $log->info( "\tThere were no targetable copies for the hold" );
1866 process_recall($actor, $log, $hold, \@good_copies);
1869 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1870 $log->info("\tProcessing of hold ".$hold->id." complete.");
1873 { hold => $hold->id,
1874 old_target => ($old_best ? $old_best->id : undef),
1875 eligible_copies => $copy_count,
1876 target => ($best ? $best->id : undef),
1877 found_copy => $found_copy };
1882 $log->error("Processing of hold failed: $e");
1883 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1884 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1891 __PACKAGE__->register_method(
1892 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1894 method => 'new_hold_copy_targeter',
1897 sub process_recall {
1898 my ($actor, $log, $hold, $good_copies) = @_;
1900 # Bail early if we don't have required settings to avoid spurious requests
1901 my ($recall_threshold, $return_interval, $fine_rules);
1903 my $rv = $actor->request(
1904 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1908 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1911 $recall_threshold = $rv->{value};
1913 $rv = $actor->request(
1914 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1918 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1921 $return_interval = $rv->{value};
1923 $rv = $actor->request(
1924 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1928 $fine_rules = $rv->{value};
1931 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1933 # We want checked out copies (status = 1) at the hold pickup lib
1934 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1936 my @copy_ids = map { $_->id } @$all_copies;
1938 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1940 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1942 # Iterate over the checked-out copies to find a copy with a
1943 # loan period longer than the recall threshold:
1944 my $circs = [ action::circulation->search_where(
1945 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1946 { order_by => 'due_date ASC' }
1949 # If we have a candidate copy, then:
1950 if (scalar(@$circs)) {
1951 my $circ = $circs->[0];
1952 $log->info("Recalling circ ID : " . $circ->id);
1954 # Give the user a new due date of either a full recall threshold,
1955 # or the return interval, whichever is further in the future
1956 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1957 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1958 $return_date = $threshold_date;
1961 my $update_fields = {
1962 due_date => $return_date,
1963 renewal_remaining => 0,
1966 # If the OU hasn't defined new fine rules for recalls, keep them
1969 $log->info("Apply recall fine rules: $fine_rules");
1970 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1971 $update_fields->{recurring_fine} = $rules->[0];
1972 $update_fields->{fine_interval} = $rules->[1];
1973 $update_fields->{max_fine} = $rules->[2];
1976 # Adjust circ for current user
1977 $circ->update($update_fields);
1979 # Create trigger event for notifying current user
1980 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1981 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1984 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1987 sub reservation_targeter {
1990 my $one_reservation = shift;
1992 local $OpenILS::Application::Storage::WRITE = 1;
1997 if ($one_reservation) {
1998 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1999 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
2002 # find all the reservations needing targeting
2004 booking::reservation->search_where(
2005 { current_resource => undef,
2006 cancel_time => undef,
2007 start_time => { '>' => 'now' }
2009 { order_by => 'start_time' }
2013 } catch Error with {
2015 die "Could not retrieve reservation requests:\n\n$e\n";
2019 for my $bresv (@$reservations) {
2021 #start a transaction if needed
2022 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
2023 $log->debug("Cleaning up after previous transaction\n");
2024 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
2026 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
2027 $log->info("Processing reservation ".$bresv->id."...\n");
2029 #first, re-fetch the hold, to make sure it's not captured already
2030 $bresv->remove_from_object_index();
2031 $bresv = booking::reservation->retrieve( $bresv->id );
2033 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
2035 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
2036 if (DateTime->compare($end_time, DateTime->now) < 0) {
2038 # cancel cause = un-targeted expiration
2039 $bresv->update( { cancel_time => 'now' } );
2041 # refresh fields from the DB while still in the xact
2042 my $fm_bresv = $bresv->to_fieldmapper;
2044 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2046 # tell A/T the reservation was cancelled
2047 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
2048 $ses->request('open-ils.trigger.event.autocreate',
2049 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
2054 my $possible_resources;
2056 # find all the potential resources
2057 if (!$bresv->target_resource) {
2058 my $filter = { type => $bresv->target_resource_type };
2059 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
2061 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
2063 $filter->{available} = [$bresv->start_time, $bresv->end_time];
2064 my $ses = OpenSRF::AppSession->create('open-ils.booking');
2065 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
2067 $possible_resources = $bresv->target_resource;
2070 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
2071 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
2074 my @good_resources = ();
2076 for my $res (@$all_resources) {
2077 unless (isTrue($res->type->catalog_item)) {
2078 push @good_resources, $res;
2082 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
2085 push @good_resources, $res;
2089 # At this point, if we're just targeting one specific
2090 # resource, just succeed. We don't care about its present
2092 if ($bresv->target_resource) {
2093 push @good_resources, $res;
2097 if ($copy->status->id == 0 || $copy->status->id == 7) {
2098 push @good_resources, $res;
2102 if ($copy->status->id == 1) {
2103 my $circs = [ action::circulation->search_where(
2104 {target_copy => $copy->id, checkin_time => undef },
2105 { order_by => 'id DESC' }
2109 my $due_date = $circs->[0]->due_date;
2110 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
2111 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
2112 if (DateTime->compare($start_time, $due_date) < 0) {
2113 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
2117 push @good_resources, $res;
2123 push @good_resources, $res if (isTrue($copy->status->holdable));
2126 # let 'em know we're still working
2127 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2129 # if we have no copies ...
2130 if (!@good_resources) {
2131 $log->info("\tNo resources available for targeting at all!\n");
2132 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
2135 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2139 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
2141 # LFW: note that after the inclusion of hold proximity
2142 # adjustment, this prox_list is the only prox_list
2143 # array in this perl package. Other occurences are
2149 $_->owner == $bresv->pickup_lib
2153 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
2154 # $all_copies is now a list of copies not at the pickup library
2156 my $best = shift @good_resources;
2157 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2160 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
2164 sort { $a->[0] <=> $b->[0] }
2166 [ actor::org_unit_proximity->search_where(
2167 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
2173 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2175 $best = shift @$prox_list
2179 $bresv->update( { current_resource => ''.$best->id } );
2180 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
2183 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2184 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
2187 { reservation => $bresv->id,
2188 current_resource => ($best ? $best->id : undef) };
2193 $log->error("Processing of bresv failed: $e");
2194 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
2195 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
2202 __PACKAGE__->register_method(
2203 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
2205 method => 'reservation_targeter',
2210 my %cache = (titles => {}, cns => {});
2212 sub copy_hold_capture {
2217 if (!defined($cps)) {
2219 $cps = [ asset::copy->search( id => $hold->target ) ];
2220 } catch Error with {
2222 die "Could not retrieve initial volume list:\n\n$e\n";
2226 my @copies = grep { $_->holdable } @$cps;
2228 for (my $i = 0; $i < @$cps; $i++) {
2229 next unless $$cps[$i];
2231 my $cn = $cache{cns}{$copies[$i]->call_number};
2232 my $rec = $cache{titles}{$cn->record};
2233 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
2234 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
2235 $copies[$i] = undef if (
2237 !$self->{user_filter}->request(
2238 'open-ils.circ.permit_hold',
2239 $hold->to_fieldmapper, do {
2240 my $cp_fm = $copies[$i]->to_fieldmapper;
2241 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
2242 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
2243 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
2246 { title => $rec->to_fieldmapper,
2247 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
2248 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
2251 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
2254 @copies = grep { $_ } @copies;
2256 my $count = @copies;
2258 return unless ($count);
2260 action::hold_copy_map->search( hold => $hold->id )->delete_all;
2263 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
2264 for my $c (@copies) {
2265 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
2267 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
2273 sub choose_nearest_copy {
2275 my $prox_list = shift;
2277 for my $p ( sort keys %$prox_list ) {
2278 next unless (ref $$prox_list{$p});
2280 my @capturable = @{ $$prox_list{$p} };
2281 next unless (@capturable);
2283 my $rand = int(rand(scalar(@capturable)));
2285 while (my ($c) = splice(@capturable, $rand, 1)) {
2286 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
2287 { title => $c->call_number->record->to_fieldmapper,
2288 patron => $hold->usr->to_fieldmapper,
2289 copy => $c->to_fieldmapper,
2290 requestor => $hold->requestor->to_fieldmapper,
2291 request_lib => $hold->request_lib->to_fieldmapper,
2292 pickup_lib => $hold->pickup_lib->id,
2298 last unless(@capturable);
2299 $rand = int(rand(scalar(@capturable)));
2304 sub create_prox_list {
2309 my $hold_copy_map = shift || {};
2312 my $editor = new_editor;
2313 for my $cp (@$copies) {
2314 my $prox = $hold_copy_map->{"$hold"}->{"$cp"}; # Allow CDBI stringification to get the pkey
2315 ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib, $hold ) unless (defined $prox);
2316 next unless (defined($prox));
2318 my $copy_circ_lib = ''.$cp->circ_lib;
2319 # Fetch the weighting value for hold targeting, defaulting to 1
2320 $self->{target_weight}{$copy_circ_lib} ||= $U->ou_ancestor_setting(
2321 $copy_circ_lib.'', 'circ.holds.org_unit_target_weight', $editor
2323 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
2324 $self->{target_weight}{$copy_circ_lib} ||= 1;
2326 $prox_list{$prox} = [] unless defined($prox_list{$prox});
2327 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
2328 push @{$prox_list{$prox}}, $cp;
2334 sub volume_hold_capture {
2339 if (!defined($vols)) {
2341 $vols = [ asset::call_number->search( id => $hold->target ) ];
2342 $cache{cns}{$_->id} = $_ for (@$vols);
2343 } catch Error with {
2345 die "Could not retrieve initial volume list:\n\n$e\n";
2349 my @v_ids = map { $_->id } @$vols;
2353 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
2355 } catch Error with {
2357 warn "Could not retrieve copy list:\n\n$e\n";
2360 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
2363 sub title_hold_capture {
2368 if (!defined($titles)) {
2370 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
2371 $cache{titles}{$_->id} = $_ for (@$titles);
2372 } catch Error with {
2374 die "Could not retrieve initial title list:\n\n$e\n";
2378 my @t_ids = map { $_->id } @$titles;
2381 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
2383 } catch Error with {
2385 warn "Could not retrieve volume list:\n\n$e\n";
2388 $cache{cns}{$_->id} = $_ for (@$cn_list);
2390 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);