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;
13 use DateTime::Format::ISO8601;
14 use OpenILS::Utils::Penalty;
16 use OpenILS::Application::Circ::CircCommon;
17 use OpenILS::Application::AppUtils;
18 my $U = "OpenILS::Application::AppUtils";
20 # used in build_hold_sort_clause()
21 my %HOLD_SORT_ORDER_BY = (
23 hprox => 'actor.org_unit_proximity(%d, h.request_lib)', # $cp->circ_lib
24 aprox => 'COALESCE(hm.proximity, p.prox)',
25 approx => 'action.hold_copy_calculated_proximity(h.id, %d, %d)', # $cp,$here
26 priority => 'pgt.hold_priority',
27 cut => 'CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END',
28 depth => 'h.selection_depth',
29 rtime => 'h.request_time',
32 copy_has_not_been_home.result
33 THEN actor.org_unit_proximity(%d, h.request_lib)
39 copy_has_not_been_home_even_to_idle.result
40 THEN actor.org_unit_proximity(%d, h.request_lib)
49 return 1 if ($v == 1);
50 return 1 if ($v =~ /^t/io);
51 return 1 if ($v =~ /^y/io);
55 sub ou_ancestor_setting_value_or_cache {
56 # cache should be specific to setting
57 my ($actor, $org_id, $setting, $cache) = @_;
59 if (not exists $cache->{$org_id}) {
60 my $r = $actor->request(
61 'open-ils.actor.ou_setting.ancestor_default', $org_id, $setting
65 $cache->{$org_id} = $r->{value};
67 $cache->{$org_id} = undef;
70 return $cache->{$org_id};
73 my $parser = DateTime::Format::ISO8601->new;
74 my $log = 'OpenSRF::Utils::Logger';
76 sub open_noncat_circs {
81 my $a = action::non_cataloged_circulation->table;
82 my $c = config::non_cataloged_type->table;
87 JOIN $c c ON (a.item_type = c.id)
88 WHERE a.circ_time + c.circ_duration > current_timestamp
92 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
94 __PACKAGE__->register_method(
95 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
96 method => 'open_noncat_circs',
102 sub ou_hold_requests {
107 my $h_table = action::hold_request->table;
108 my $c_table = asset::copy->table;
109 my $o_table = actor::org_unit->table;
114 JOIN $c_table cp ON (cp.id = h.current_copy)
115 JOIN $o_table ou ON (ou.id = cp.circ_lib)
117 AND h.capture_time IS NULL
118 AND h.cancel_time IS NULL
119 AND (h.expire_time IS NULL OR h.expire_time > NOW())
120 ORDER BY h.request_time
123 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
126 $client->respond($_) for (
129 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
133 } @{ $sth->fetchall_arrayref }
137 __PACKAGE__->register_method(
138 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
142 method => 'ou_hold_requests',
147 my $upper_interval = shift || '1 millennium';
150 my $c_t = action::circulation->table;
155 WHERE stop_fines IS NULL
156 AND due_date < ( CURRENT_TIMESTAMP - grace_period )
157 AND fine_interval < ?::INTERVAL
160 my $sth = action::circulation->db_Main->prepare_cached($sql);
161 $sth->execute($upper_interval);
163 my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
165 $c_t = booking::reservation->table;
169 WHERE return_time IS NULL
170 AND end_time < ( CURRENT_TIMESTAMP )
171 AND fine_interval IS NOT NULL
172 AND cancel_time IS NULL
175 $sth = action::circulation->db_Main->prepare_cached($sql);
178 push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
183 sub complete_reshelving {
188 local $OpenILS::Application::Storage::WRITE = 1;
190 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
191 unless (interval_to_seconds( $window ));
193 my $cp = asset::copy->table;
202 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)
205 my $sth = action::circulation->db_Main->prepare_cached($sql);
206 $sth->execute($window);
211 __PACKAGE__->register_method(
212 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
215 method => 'complete_reshelving',
218 sub mark_longoverdue {
223 local $OpenILS::Application::Storage::WRITE = 1;
225 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
226 unless (interval_to_seconds( $window ));
228 my $setting = actor::org_unit_setting->table;
229 my $circ = action::circulation->table;
233 SET stop_fines = 'LONGOVERDUE',
234 stop_fines_time = now()
238 LEFT JOIN $setting setting
239 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
240 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
241 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
245 my $sth = action::circulation->db_Main->prepare_cached($sql);
246 $sth->execute($window);
251 __PACKAGE__->register_method(
252 api_name => 'open-ils.storage.action.circulation.long_overdue',
255 method => 'mark_longoverdue',
258 sub auto_thaw_frozen_holds {
262 local $OpenILS::Application::Storage::WRITE = 1;
264 my $holds = action::hold_request->table;
266 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
268 my $sth = action::hold_request->db_Main->prepare_cached($sql);
274 __PACKAGE__->register_method(
275 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
279 method => 'auto_thaw_frozen_holds',
286 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
288 $client->respond( $idlist ? $_ : $_->to_fieldmapper ) for ( overdue_circs('', $idlist) );
293 __PACKAGE__->register_method(
294 api_name => 'open-ils.storage.action.circulation.overdue',
297 method => 'grab_overdue',
299 Return list of overdue circulations and reservations to be used for fine generation.
300 Despite the name, this is not a generic method for retrieving all overdue loans,
301 as it excludes loans that have already hit the maximum fine limit.
304 __PACKAGE__->register_method(
305 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
308 method => 'grab_overdue',
311 sub get_hold_sort_order {
314 my $dbh = action::hold_request->db_Main;
316 # The purpose of this function is to return column names in a DB-configured
317 # order, so it won't do to add columns here or change column names unless
318 # you also change the expectation of anything calling this function.
320 my $row = $dbh->selectrow_hashref(
323 cbho.pprox, cbho.hprox, cbho.aprox, cbho.approx, cbho.priority,
324 cbho.cut, cbho.depth, cbho.htime, cbho.shtime, cbho.rtime
325 FROM config.best_hold_order cbho
327 SELECT oils_json_to_text(value)::INT
328 FROM actor.org_unit_ancestor_setting('circ.hold_capture_order', ?)
332 pprox => 1, hprox => 8, aprox => 2, priority => 3,
333 cut => 4, depth => 5, htime => 7, rtime => 6
336 # Return only the keys of our hash, sorted by value,
337 # keys for null values omitted.
339 grep { defined $row->{$_} } (
340 sort {$row->{$a} cmp $row->{$b}} keys %$row
345 # Returns an ORDER BY clause
346 # *and* a string with a CTE expression to precede the nearest-hold SQL query
347 # *and* a string with extra JOIN statements needed
348 sub build_hold_sort_clause {
349 my ($columns, $cp, $here) = @_;
351 my %order_by_sprintf_args = (
352 hprox => [$cp->circ_lib],
353 approx => [$cp->id, $here],
354 htime => [$cp->circ_lib],
355 shtime => [$cp->circ_lib]
360 foreach my $col (@$columns) {
361 if ($col eq 'htime' and not $ctes_needed) {
363 } elsif ($col eq 'shtime') {
368 @args = @{$order_by_sprintf_args{$col}} if
369 exists $order_by_sprintf_args{$col};
371 push @clauses, sprintf($HOLD_SORT_ORDER_BY{$col}, @args);
373 last if $col eq 'rtime'; # rtime is effectively unique, no need for
374 # more order-by clauses after that.
378 if ($ctes_needed >= 1) {
379 # For our first auxiliary query, the question we seek to answer is, "has
380 # our copy been circulating away from home too long?" Two parts to
381 # answer this question.
383 # part 1: Have their been no checkouts at the copy's circ_lib since the
384 # beginning of our go-home interval?
385 # part 2: Was the last transit to affect our copy before the beginning
386 # of our go-home interval an outbound transit? i.e. away from circ-lib
388 # [We use sprintf because the outer function that's going to send one
389 # big query through DBI is blind to our process of dynamically building
390 # these CTEs, and it wouldn't know what bind parameters to pass unless
391 # we did a lot more work here. This is injection-safe because we only
392 # use the %d formatter.]
394 , copy_has_not_been_home AS (
397 SELECT circ.id FROM action.circulation circ
398 JOIN go_home_interval ON (true)
400 circ.target_copy = %d AND
401 circ.circ_lib = %d AND
402 circ.xact_start >= NOW() - go_home_interval.value
405 SELECT atc.dest <> %d FROM action.transit_copy atc
406 JOIN go_home_interval ON (true)
409 SELECT MAX(id) FROM action.transit_copy atc_inner
411 atc_inner.target_copy = %d AND
412 atc_inner.source_send_time < NOW() - go_home_interval.value
415 ) !, $cp->id, $cp->circ_lib, $cp->circ_lib, $cp->id);
416 $joins .= " JOIN copy_has_not_been_home ON (true) ";
419 if ($ctes_needed == 2) {
420 # In this auxiliary query, we ask the question, "has our copy come home
421 # by any means that we can determine, even if it didn't circulate once
422 # it came home, in the time defined by the go-home-interval?"
423 # answer this question. Two parts to this too (besides including the
424 # previous auxiliary query).
426 # 1: there have been no homebound transits for this copy since the
427 # beginning of the go-home interval.
428 # 2: there have been no checkins at home since the beginning of
429 # the go-home interval for this copy
432 , copy_has_not_been_home_even_to_idle AS (
434 copy_has_not_been_home.response AND (
436 SELECT atc.id FROM action.transit_copy atc
437 JOIN go_home_interval ON (true)
439 atc.target_copy = %d AND
441 atc.dest_recv_time >= NOW() - go_home_interval.value
444 SELECT circ.id FROM action.circulation circ
445 JOIN go_home_interval ON (true)
447 circ.target_copy = %d AND
448 circ.checkin_lib = %d AND
449 circ.checkin_time >= NOW() - go_home_interval.value
452 ) !, $cp->id, $cp->circ_lib, $cp->id, $cp->circ_lib);
453 $joins .= " JOIN copy_has_not_been_home_even_to_idle ON (true) ";
457 join(", ", @clauses),
466 my $here = shift; # just the ID
467 my $cp = shift; # now an object, formerly just the ID
468 my $limit = int(shift()) || 10;
469 my $age = shift() || '0 seconds';
472 $log->info("deprecated 'fifo' param true, but ignored") if isTrue $fifo;
474 my ($holdsort, $addl_cte, $addl_join) =
475 build_hold_sort_clause(get_hold_sort_order($here), $cp, $here);
477 local $OpenILS::Application::Storage::WRITE = 1;
479 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $cp->circ_lib, $here, $cp->id, $age);
480 WITH go_home_interval AS (
481 SELECT OILS_JSON_TO_TEXT(
482 (SELECT value FROM actor.org_unit_ancestor_setting(
483 'circ.hold_go_home_interval', ?
485 ))::INTERVAL AS value
489 FROM action.hold_request h
490 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
491 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
492 JOIN actor.usr au ON (au.id = h.usr)
493 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
494 LEFT JOIN actor.usr_standing_penalty ausp
495 ON ( au.id = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
496 LEFT JOIN config.standing_penalty csp
497 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
499 WHERE hm.target_copy = ?
500 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
501 AND h.capture_time IS NULL
502 AND h.cancel_time IS NULL
503 AND (h.expire_time IS NULL OR h.expire_time > NOW())
504 AND h.frozen IS FALSE
506 ORDER BY CASE WHEN h.hold_type IN ('R','F') THEN 0 ELSE 1 END, $holdsort
510 $client->respond( $_ ) for ( @$ids );
513 __PACKAGE__->register_method(
514 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
517 method => 'nearest_hold',
520 sub targetable_holds {
523 my $check_expire = shift;
525 $check_expire ||= '12h';
527 local $OpenILS::Application::Storage::WRITE = 1;
529 # json_query can *almost* represent this query, but can't
530 # handle the CASE statement or the interval arithmetic
531 my $query = <<" SQL";
532 SELECT ahr.id, mmsm.metarecord
533 FROM action.hold_request ahr
534 JOIN reporter.hold_request_record USING (id)
535 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
536 WHERE capture_time IS NULL
537 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
538 AND fulfillment_time IS NULL
539 AND cancel_time IS NULL
541 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
543 my $sth = action::hold_request->db_Main->prepare_cached($query);
544 $sth->execute($check_expire);
545 $client->respond( $_ ) for @{ $sth->fetchall_arrayref };
550 __PACKAGE__->register_method(
551 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
554 method => 'targetable_holds',
556 Returns ordered list of hold request and metarecord IDs
557 for all hold requests that are available for initial targeting
559 @param check interval
560 @return list of pairs of hold request and metarecord IDs
564 sub next_resp_group_id {
568 # XXX This is not replication safe!!!
570 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
571 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
575 __PACKAGE__->register_method(
576 api_name => 'open-ils.storage.action.survey_response.next_group_id',
578 method => 'next_resp_group_id',
581 sub patron_circ_summary {
586 return undef unless ($id);
587 my $c_table = action::circulation->table;
588 my $b_table = money::billing->table;
590 $log->debug("Retrieving patron summary for id $id", DEBUG);
592 my $select = <<" SQL";
593 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
595 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
597 AND c.xact_finish IS NULL
599 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
600 OR c.stop_fines IS NULL
604 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
606 __PACKAGE__->register_method(
607 api_name => 'open-ils.storage.action.circulation.patron_summary',
609 method => 'patron_circ_summary',
612 #XXX Fix stored proc calls
613 sub find_local_surveys {
618 return undef unless ($ou);
619 my $s_table = action::survey->table;
621 my $select = <<" SQL";
624 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
625 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
628 my $sth = action::survey->db_Main->prepare_cached($select);
631 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
635 __PACKAGE__->register_method(
636 api_name => 'open-ils.storage.action.survey.all',
639 method => 'find_local_surveys',
642 #XXX Fix stored proc calls
643 sub find_opac_surveys {
648 return undef unless ($ou);
649 my $s_table = action::survey->table;
651 my $select = <<" SQL";
654 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
655 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
659 my $sth = action::survey->db_Main->prepare_cached($select);
662 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
666 __PACKAGE__->register_method(
667 api_name => 'open-ils.storage.action.survey.opac',
670 method => 'find_opac_surveys',
677 my $limit = shift || 10;
678 my $offset = shift || 0;
680 return undef unless ($ou);
681 my $h_table = action::hold_request->table;
682 my $a_table = asset::copy->table;
683 my $ord_table = asset::copy_location_order->table;
685 my $idlist = 1 if ($self->api_name =~/id_list/o);
686 my $count = 1 if ($self->api_name =~/count$/o);
688 my $status_filter = '';
689 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
691 my $select = <<" SQL";
694 JOIN $a_table a ON (h.current_copy = a.id)
695 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
696 LEFT JOIN actor.usr_standing_penalty ausp
697 ON ( h.usr = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
698 LEFT JOIN config.standing_penalty csp
699 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
701 AND h.capture_time IS NULL
702 AND h.cancel_time IS NULL
703 AND (h.expire_time IS NULL OR h.expire_time > NOW())
706 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
715 JOIN $a_table a ON (h.current_copy = a.id)
716 LEFT JOIN actor.usr_standing_penalty ausp
717 ON ( h.usr = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
718 LEFT JOIN config.standing_penalty csp
719 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
721 AND h.capture_time IS NULL
722 AND h.cancel_time IS NULL
723 AND (h.expire_time IS NULL OR h.expire_time > NOW())
729 my $sth = action::survey->db_Main->prepare_cached($select);
733 $client->respond( $sth->fetchall_arrayref()->[0][0] );
735 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
737 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
742 __PACKAGE__->register_method(
743 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
747 "Returns a count of holds for a specific library's pull list.",
748 [ [org_unit => "The library's org id", "number"] ],
749 ['A count of holds for the stated library to pull ', 'number']
751 method => 'hold_pull_list',
753 __PACKAGE__->register_method(
754 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
758 "Returns a status filtered count of holds for a specific library's pull list.",
759 [ [org_unit => "The library's org id", "number"] ],
760 ['A status filtered count of holds for the stated library to pull ', 'number']
762 method => 'hold_pull_list',
764 __PACKAGE__->register_method(
765 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
769 "Returns the hold ids for a specific library's pull list.",
770 [ [org_unit => "The library's org id", "number"],
771 [limit => 'An optional page size, defaults to 10', 'number'],
772 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
774 ['A list of holds for the stated library to pull for', 'array']
776 method => 'hold_pull_list',
778 __PACKAGE__->register_method(
779 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
783 "Returns the holds for a specific library's pull list.",
784 [ [org_unit => "The library's org id", "number"],
785 [limit => 'An optional page size, defaults to 10', 'number'],
786 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
788 ['A list of holds for the stated library to pull for', 'array']
790 method => 'hold_pull_list',
792 __PACKAGE__->register_method(
793 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
797 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
798 [ [org_unit => "The library's org id", "number"],
799 [limit => 'An optional page size, defaults to 10', 'number'],
800 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
802 ['A list of holds for the stated library to pull for', 'array']
804 method => 'hold_pull_list',
806 __PACKAGE__->register_method(
807 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
811 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
812 [ [org_unit => "The library's org id", "number"],
813 [limit => 'An optional page size, defaults to 10', 'number'],
814 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
816 ['A list of holds for the stated library to pull for', 'array']
818 method => 'hold_pull_list',
821 sub find_optional_surveys {
826 return undef unless ($ou);
827 my $s_table = action::survey->table;
829 my $select = <<" SQL";
832 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
833 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
834 AND s.required IS FALSE;
837 my $sth = action::survey->db_Main->prepare_cached($select);
840 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
844 __PACKAGE__->register_method(
845 api_name => 'open-ils.storage.action.survey.optional',
848 method => 'find_optional_surveys',
851 sub find_required_surveys {
856 return undef unless ($ou);
857 my $s_table = action::survey->table;
859 my $select = <<" SQL";
862 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
863 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
864 AND s.required IS TRUE;
867 my $sth = action::survey->db_Main->prepare_cached($select);
870 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
874 __PACKAGE__->register_method(
875 api_name => 'open-ils.storage.action.survey.required',
878 method => 'find_required_surveys',
881 sub find_usr_summary_surveys {
886 return undef unless ($ou);
887 my $s_table = action::survey->table;
889 my $select = <<" SQL";
892 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
893 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
894 AND s.usr_summary IS TRUE;
897 my $sth = action::survey->db_Main->prepare_cached($select);
900 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
904 __PACKAGE__->register_method(
905 api_name => 'open-ils.storage.action.survey.usr_summary',
908 method => 'find_usr_summary_surveys',
911 sub seconds_to_interval_hash {
912 my $interval = shift;
913 my $limit = shift || 's';
914 $limit =~ s/^(.)/$1/o;
918 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
919 my ($year, $month, $week, $day, $hour, $minute, $second) =
920 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
922 if ($y = int($interval / (60 * 60 * 24 * 365))) {
924 $ym = $interval % (60 * 60 * 24 * 365);
928 return %output if ($limit eq 'y');
930 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
931 $output{$month} = $M;
932 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
936 return %output if ($limit eq 'M');
938 if ($w = int($Mm / 604800)) {
944 return %output if ($limit eq 'w');
946 if ($d = int($wm / 86400)) {
952 return %output if ($limit eq 'd');
954 if ($h = int($dm / 3600)) {
960 return %output if ($limit eq 'h');
962 if ($m = int($hm / 60)) {
963 $output{$minute} = $m;
968 return %output if ($limit eq 'm');
971 $output{$second} = $s;
973 $output{$second} = 0 unless (keys %output);
983 my $overbill = shift;
985 local $OpenILS::Application::Storage::WRITE = 1;
990 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
991 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
993 push @circs, overdue_circs();
996 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
998 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
1001 my $ctype = ref($c);
1002 $ctype =~ s/^.+::(\w+)$/$1/;
1004 my $due_date_method = 'due_date';
1005 my $target_copy_method = 'target_copy';
1006 my $circ_lib_method = 'circ_lib';
1007 my $recurring_fine_method = 'recurring_fine';
1008 my $is_reservation = 0;
1009 if ($ctype eq 'reservation') {
1010 $is_reservation = 1;
1011 $due_date_method = 'end_time';
1012 $target_copy_method = 'current_resource';
1013 $circ_lib_method = 'pickup_lib';
1014 $recurring_fine_method = 'fine_amount';
1015 next unless ($c->fine_interval);
1017 #TODO: reservation grace periods
1018 my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
1021 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1022 $log->debug("Cleaning up after previous transaction\n");
1023 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1025 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1027 sprintf("Processing %s %d...",
1028 ($is_reservation ? "reservation" : "circ"), $c->id
1033 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
1035 my $due = $due_dt->epoch;
1038 my $fine_interval = $c->fine_interval;
1039 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
1040 $fine_interval = interval_to_seconds( $fine_interval );
1042 if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
1043 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
1044 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
1048 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
1049 my $tz_offset_s = 0;
1050 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
1051 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
1054 $due -= ($due % $fine_interval) + $tz_offset_s;
1055 $now -= ($now % $fine_interval) + $tz_offset_s;
1059 "ARG! Overdue $ctype ".$c->id.
1060 " for item ".$c->$target_copy_method.
1061 " (user ".$c->usr.").\n".
1062 "\tItem was due on or before: ".localtime($due)."\n");
1064 my @fines = money::billing->search_where(
1067 billing_ts => { '>' => $c->$due_date_method } },
1068 { order_by => 'billing_ts DESC'}
1072 my $fine = $fines[$f_idx] if (@fines);
1074 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
1077 my $current_fine_total = 0;
1078 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
1082 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
1083 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
1085 $log->info( "Potential first billing for circ ".$c->id );
1088 $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});
1091 next if ($last_fine > $now);
1092 # Generate fines for each past interval, including the one we are inside
1093 my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
1095 if ( $last_fine == $due # we have no fines yet
1096 && $grace_period # and we have a grace period
1097 && $now < $due + $grace_period # and some date math says were are within the grace period
1099 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
1100 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
1104 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
1105 next unless ($pending_fine_count);
1107 my $recurring_fine = int($c->$recurring_fine_method * 100);
1108 my $max_fine = int($c->max_fine * 100);
1110 my $skip_closed_check = $U->ou_ancestor_setting_value(
1111 $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.charge_when_closed');
1112 $skip_closed_check = $U->is_true($skip_closed_check);
1114 my ($latest_billing_ts, $latest_amount) = ('',0);
1115 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
1117 if ($current_fine_total >= $max_fine) {
1118 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
1120 "\tMaximum fine level of ".$c->max_fine.
1121 " reached for this $ctype.\n".
1122 "\tNo more fines will be generated.\n" );
1126 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
1127 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
1128 my $current_bill_count = $bill;
1129 while ( $current_bill_count ) {
1130 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
1131 $current_bill_count--;
1134 my $timestamptz = $billing_ts->strftime('%FT%T%z');
1135 if (!$skip_closed_check) {
1136 my $dow = $billing_ts->day_of_week_0();
1137 my $dow_open = "dow_${dow}_open";
1138 my $dow_close = "dow_${dow}_close";
1140 if (my $h = $hoo{$c->$circ_lib_method}) {
1141 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
1144 my @cl = actor::org_unit::closed_date->search_where(
1145 { close_start => { '<=' => $timestamptz },
1146 close_end => { '>=' => $timestamptz },
1147 org_unit => $c->$circ_lib_method }
1152 $current_fine_total += $recurring_fine;
1153 $latest_amount += $recurring_fine;
1154 $latest_billing_ts = $timestamptz;
1156 money::billing->create(
1157 { xact => ''.$c->id,
1158 note => "System Generated Overdue Fine",
1159 billing_type => "Overdue materials",
1161 amount => sprintf('%0.2f', $recurring_fine/100),
1162 billing_ts => $timestamptz,
1168 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
1169 if ($latest_billing_ts and $latest_amount);
1171 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1175 # Caluclate penalties inline
1176 OpenILS::Utils::Penalty->calculate_penalties(
1177 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
1181 # Calculate penalties with an aysnc call to the penalty server. This approach
1182 # may lead to duplicate penalties since multiple penalty processes for a
1183 # given user may be running at the same time. Leave this here for reference
1184 # in case we later find that asyc calls are needed in some environments.
1186 'open-ils.penalty.patron_penalty.calculate',
1187 { patronid => ''.$c->usr,
1188 context_org => ''.$c->$circ_lib_method,
1195 } catch Error with {
1197 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
1198 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
1199 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1200 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1204 __PACKAGE__->register_method(
1205 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1208 method => 'generate_fines',
1213 sub new_hold_copy_targeter {
1216 my $check_expire = shift;
1217 my $one_hold = shift;
1218 my $find_copy = shift;
1220 local $OpenILS::Application::Storage::WRITE = 1;
1222 $self->{target_weight} = {};
1223 $self->{max_loops} = {};
1229 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1230 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
1231 } elsif ( $check_expire ) {
1233 # what's the retarget time threashold?
1235 $check_expire ||= '12h';
1236 $check_expire = interval_to_seconds( $check_expire );
1238 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1241 my $expire_threshold = sprintf(
1242 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1243 $year, $mon, $mday, $hour, $min, $sec
1246 # find all the holds holds needing retargeting
1247 $holds = [ action::hold_request->search_where(
1248 { capture_time => undef,
1249 fulfillment_time => undef,
1250 cancel_time => undef,
1252 prev_check_time => { '<=' => $expire_threshold },
1254 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
1256 # find all the holds holds needing first time targeting
1257 push @$holds, action::hold_request->search(
1258 capture_time => undef,
1259 fulfillment_time => undef,
1260 prev_check_time => undef,
1262 cancel_time => undef,
1263 { order_by => 'selection_depth DESC, request_time' } );
1266 # find all the holds holds needing first time targeting ONLY
1267 $holds = [ action::hold_request->search(
1268 capture_time => undef,
1269 fulfillment_time => undef,
1270 prev_check_time => undef,
1271 cancel_time => undef,
1273 { order_by => 'selection_depth DESC, request_time' } ) ];
1275 } catch Error with {
1277 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1280 my @closed = actor::org_unit::closed_date->search_where(
1281 { close_start => { '<=', 'now' },
1282 close_end => { '>=', 'now' } }
1285 if ($check_expire) {
1287 # $check_expire, if it exists, was already converted to seconds
1288 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1292 my $next_check_time = sprintf(
1293 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1294 $year, $mon, $mday, $hour, $min, $sec
1298 my @closed_at_next = actor::org_unit::closed_date->search_where(
1299 { close_start => { '<=', $next_check_time },
1300 close_end => { '>=', $next_check_time } }
1304 for my $c_at_n (@closed_at_next) {
1305 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1306 push @new_closed, $c_at_n;
1309 @closed = @new_closed;
1313 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1315 my $target_when_closed = {};
1316 my $target_when_closed_if_at_pickup_lib = {};
1318 for my $hold (@$holds) {
1320 #start a transaction if needed
1321 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1322 $log->debug("Cleaning up after previous transaction\n");
1323 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1325 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1326 $log->info("Processing hold ".$hold->id."...\n");
1328 #first, re-fetch the hold, to make sure it's not captured already
1329 $hold->remove_from_object_index();
1330 $hold = action::hold_request->retrieve( $hold->id );
1332 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1334 # remove old auto-targeting maps
1335 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1336 $_->delete for (@oldmaps);
1338 if ($hold->expire_time) {
1339 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1340 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1342 # cancel cause = un-targeted expiration
1343 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1345 # refresh fields from the DB while still in the xact
1346 my $fm_hold = $hold->to_fieldmapper;
1348 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1350 # tell A/T the hold was cancelled
1351 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1352 $ses->request('open-ils.trigger.event.autocreate',
1353 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1359 my $all_copies = [];
1361 # find filters for MR holds
1362 my ($types, $formats, $lang);
1363 if (defined($hold->holdable_formats)) {
1364 ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1367 # find all the potential copies
1368 if ($hold->hold_type eq 'M') {
1371 isTrue($_->deleted) ? () : ($_->id)
1372 } metabib::metarecord->retrieve($hold->target)->source_records
1377 metabib::record_descriptor
1380 ( $types ? (item_type => [split '', $types]) : () ),
1381 ( $formats ? (item_form => [split '', $formats]) : () ),
1382 ( $lang ? (item_lang => $lang) : () ),
1386 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1387 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1389 for my $cn ( @{ $rtree->call_numbers } ) {
1391 asset::copy->search_where(
1392 { id => [map {$_->id} @{ $cn->copies }],
1394 ) if ($cn && @{ $cn->copies });
1398 } elsif ($hold->hold_type eq 'T') {
1400 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1401 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1404 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1408 for my $cn ( @{ $rtree->call_numbers } ) {
1410 asset::copy->search_where(
1411 { id => [map {$_->id} @{ $cn->copies }],
1413 ) if ($cn && @{ $cn->copies });
1415 } elsif ($hold->hold_type eq 'V') {
1417 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1418 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1421 asset::copy->search_where(
1422 { id => [map {$_->id} @{ $vtree->copies }],
1424 ) if ($vtree && @{ $vtree->copies });
1426 } elsif ($hold->hold_type eq 'P') {
1427 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1429 asset::copy->search_where(
1430 { id => [map {$_->target_copy} @part_maps],
1435 } elsif ($hold->hold_type eq 'I') {
1437 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1438 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1441 asset::copy->search_where(
1442 { id => [map {$_->unit->id} @{ $itree->items }],
1444 ) if ($itree && @{ $itree->items });
1446 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1447 my $_cp = asset::copy->retrieve($hold->target);
1448 push @$all_copies, $_cp if $_cp;
1451 # Force and recall holds bypass pretty much everything
1452 if ($hold->hold_type ne 'R' && $hold->hold_type ne 'F') {
1454 @$all_copies = grep { isTrue($_->status->holdable) &&
1455 isTrue($_->location->holdable) &&
1456 isTrue($_->holdable) &&
1457 !isTrue($_->deleted) &&
1458 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1459 ( ( $hold->hold_type ne 'C' && $hold->hold_type ne 'I' # Copy-level holds don't care about parts
1460 && $hold->hold_type ne 'P' ) ? $_->part_maps->count == 0 : 1)
1464 # let 'em know we're still working
1465 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1467 # if we have no copies ...
1468 if (!ref $all_copies || !@$all_copies) {
1469 $log->info("\tNo copies available for targeting at all!\n");
1470 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1472 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1473 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1477 my $copy_count = @$all_copies;
1478 my $found_copy = undef;
1479 $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1481 # map the potentials, so that we can pick up checkins
1482 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1483 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1484 my $pu_lib = ''.$hold->pickup_lib;
1485 my $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold );
1486 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1487 for my $prox ( keys %$prox_list ) {
1488 action::hold_copy_map->create( { proximity => $prox, hold => $hold->id, target_copy => $_->id } ) for (@{$$prox_list{$prox}});
1491 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1494 for my $c (@$all_copies) {
1496 next if ($hold->current_copy and $c->id eq $hold->current_copy);
1498 # skip on circ lib is closed IFF we care
1501 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1502 $ignore_closing = ou_ancestor_setting_value_or_cache(
1505 'circ.holds.target_when_closed_if_at_pickup_lib',
1506 $target_when_closed_if_at_pickup_lib
1509 if (not $ignore_closing) { # one more chance to find a reason
1510 # to ignore OU closedness.
1511 $ignore_closing = ou_ancestor_setting_value_or_cache(
1514 'circ.holds.target_when_closed',
1520 # "For hold " . $hold->id . " and copy with circ_lib " .
1521 # $c->circ_lib . " we " .
1522 # ($ignore_closing ? "ignore" : "respect")
1527 (not $ignore_closing) and
1528 (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1531 # target of another hold
1532 next if (action::hold_request
1534 { current_copy => $c->id,
1535 fulfillment_time => undef,
1536 cancel_time => undef,
1541 # we passed all three, keep it
1542 push @good_copies, $c if ($c);
1543 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1546 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1548 my $old_best = $hold->current_copy;
1549 my $old_best_still_valid = 0; # Assume no, but the next line says yes if it is still a potential.
1550 $old_best_still_valid = 1 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies );
1551 $hold->update({ current_copy => undef }) if ($old_best);
1553 if (!scalar(@good_copies)) {
1554 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1555 if ( $old_best_still_valid ) {
1556 # the old copy is still available
1557 $log->debug("\tPushing current_copy back onto the targeting list");
1558 push @good_copies, $old_best;
1560 # oops, old copy is not available
1561 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1562 $hold->update( { prev_check_time => 'today' } );
1563 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1564 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1569 # reset prox list after trimming good copies
1570 $prox_list = create_prox_list( $self, $pu_lib, \@good_copies, $hold );
1573 my $min_prox = [ sort keys %$prox_list ]->[0];
1575 if ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') { # Recall/Force holds bypass hold rules.
1576 $best = $good_copies[0] if(scalar @good_copies);
1578 $best = choose_nearest_copy($hold, { $min_prox => delete($$prox_list{$min_prox}) });
1582 for my $prox (keys %$prox_list) {
1583 push @$all_copies, @{$$prox_list{$prox}};
1586 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1589 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1591 $self->{max_loops}{$pu_lib} = $actor->request(
1592 'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1595 if (defined($self->{max_loops}{$pu_lib})) {
1596 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1598 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1599 my $circ_lib_list = [keys %circ_lib_map];
1601 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1603 # Grab the "biggest" loop for this hold so far
1604 my $current_loop = $cstore->request(
1605 'open-ils.cstore.json_query',
1607 select => { aufhmxl => ['max'] },
1609 where => { hold => $hold->id}
1613 $current_loop = $current_loop->{max} if ($current_loop);
1614 $current_loop ||= 1;
1616 my $exclude_list = $cstore->request(
1617 'open-ils.cstore.json_query.atomic',
1619 select => { aufhol => ['circ_lib'] },
1621 where => { hold => $hold->id}
1626 if ($exclude_list && @$exclude_list) {
1627 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1628 # check to see if we've used up every library in the potentials list
1629 for my $l ( @$circ_lib_list ) {
1631 for my $ex ( @$exclude_list ) {
1637 push(@keepers, $l) if ($keep);
1640 @keepers = @$circ_lib_list;
1643 $current_loop++ if (!@keepers);
1645 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1646 # We haven't exceeded max_loops yet
1648 for my $cp ( @$all_copies ) {
1649 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1652 $all_copies = [@keeper_copies];
1654 # We have, and should remove potentials and cancel the hold
1655 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1656 $_->delete for (@oldmaps);
1658 # cancel cause = un-targeted expiration
1659 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1661 # refresh fields from the DB while still in the xact
1662 my $fm_hold = $hold->to_fieldmapper;
1664 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1666 # tell A/T the hold was cancelled
1667 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1668 $ses->request('open-ils.trigger.event.autocreate',
1669 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1674 $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold );
1676 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1680 $best = choose_nearest_copy($hold, $prox_list);
1683 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1685 # hold wasn't fulfilled, record the fact
1687 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1688 action::unfulfilled_hold_list->create(
1689 { hold => ''.$hold->id,
1690 current_copy => ''.$old_best->id,
1691 circ_lib => ''.$old_best->circ_lib,
1696 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1697 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1699 $old_best_still_valid &&
1700 !action::hold_request
1702 { current_copy => $old_best->id,
1703 fulfillment_time => undef,
1704 cancel_time => undef,
1707 ( OpenILS::Utils::PermitHold::permit_copy_hold(
1708 { title => $old_best->call_number->record->to_fieldmapper,
1709 title_descriptor => $old_best->call_number->record->record_descriptor->next->to_fieldmapper,
1710 patron => $hold->usr->to_fieldmapper,
1711 copy => $old_best->to_fieldmapper,
1712 requestor => $hold->requestor->to_fieldmapper,
1713 request_lib => $hold->request_lib->to_fieldmapper,
1714 pickup_lib => $hold->pickup_lib->id,
1719 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1720 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1722 $hold->update( { prev_check_time => 'now' } );
1723 $log->info( "\tThere were no targetable copies for the hold" );
1724 process_recall($actor, $log, $hold, \@good_copies);
1727 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1728 $log->info("\tProcessing of hold ".$hold->id." complete.");
1731 { hold => $hold->id,
1732 old_target => ($old_best ? $old_best->id : undef),
1733 eligible_copies => $copy_count,
1734 target => ($best ? $best->id : undef),
1735 found_copy => $found_copy };
1740 $log->error("Processing of hold failed: $e");
1741 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1742 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1749 __PACKAGE__->register_method(
1750 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1752 method => 'new_hold_copy_targeter',
1755 sub process_recall {
1756 my ($actor, $log, $hold, $good_copies) = @_;
1758 # Bail early if we don't have required settings to avoid spurious requests
1759 my ($recall_threshold, $return_interval, $fine_rules);
1761 my $rv = $actor->request(
1762 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1766 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1769 $recall_threshold = $rv->{value};
1771 $rv = $actor->request(
1772 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1776 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1779 $return_interval = $rv->{value};
1781 $rv = $actor->request(
1782 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1786 $fine_rules = $rv->{value};
1789 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1791 # We want checked out copies (status = 1) at the hold pickup lib
1792 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1794 my @copy_ids = map { $_->id } @$all_copies;
1796 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1798 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1800 # Iterate over the checked-out copies to find a copy with a
1801 # loan period longer than the recall threshold:
1802 my $circs = [ action::circulation->search_where(
1803 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1804 { order_by => 'due_date ASC' }
1807 # If we have a candidate copy, then:
1808 if (scalar(@$circs)) {
1809 my $circ = $circs->[0];
1810 $log->info("Recalling circ ID : " . $circ->id);
1812 # Give the user a new due date of either a full recall threshold,
1813 # or the return interval, whichever is further in the future
1814 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1815 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1816 $return_date = $threshold_date;
1819 my $update_fields = {
1820 due_date => $return_date,
1821 renewal_remaining => 0,
1824 # If the OU hasn't defined new fine rules for recalls, keep them
1827 $log->info("Apply recall fine rules: $fine_rules");
1828 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1829 $update_fields->{recurring_fine} = $rules->[0];
1830 $update_fields->{fine_interval} = $rules->[1];
1831 $update_fields->{max_fine} = $rules->[2];
1834 # Adjust circ for current user
1835 $circ->update($update_fields);
1837 # Create trigger event for notifying current user
1838 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1839 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1842 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1845 sub reservation_targeter {
1848 my $one_reservation = shift;
1850 local $OpenILS::Application::Storage::WRITE = 1;
1855 if ($one_reservation) {
1856 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1857 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1860 # find all the reservations needing targeting
1862 booking::reservation->search_where(
1863 { current_resource => undef,
1864 cancel_time => undef,
1865 start_time => { '>' => 'now' }
1867 { order_by => 'start_time' }
1871 } catch Error with {
1873 die "Could not retrieve reservation requests:\n\n$e\n";
1877 for my $bresv (@$reservations) {
1879 #start a transaction if needed
1880 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1881 $log->debug("Cleaning up after previous transaction\n");
1882 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1884 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1885 $log->info("Processing reservation ".$bresv->id."...\n");
1887 #first, re-fetch the hold, to make sure it's not captured already
1888 $bresv->remove_from_object_index();
1889 $bresv = booking::reservation->retrieve( $bresv->id );
1891 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1893 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1894 if (DateTime->compare($end_time, DateTime->now) < 0) {
1896 # cancel cause = un-targeted expiration
1897 $bresv->update( { cancel_time => 'now' } );
1899 # refresh fields from the DB while still in the xact
1900 my $fm_bresv = $bresv->to_fieldmapper;
1902 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1904 # tell A/T the reservation was cancelled
1905 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1906 $ses->request('open-ils.trigger.event.autocreate',
1907 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1912 my $possible_resources;
1914 # find all the potential resources
1915 if (!$bresv->target_resource) {
1916 my $filter = { type => $bresv->target_resource_type };
1917 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1919 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1921 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1922 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1923 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1925 $possible_resources = $bresv->target_resource;
1928 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1929 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1932 my @good_resources = ();
1934 for my $res (@$all_resources) {
1935 unless (isTrue($res->type->catalog_item)) {
1936 push @good_resources, $res;
1940 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1943 push @good_resources, $res;
1947 # At this point, if we're just targeting one specific
1948 # resource, just succeed. We don't care about its present
1950 if ($bresv->target_resource) {
1951 push @good_resources, $res;
1955 if ($copy->status->id == 0 || $copy->status->id == 7) {
1956 push @good_resources, $res;
1960 if ($copy->status->id == 1) {
1961 my $circs = [ action::circulation->search_where(
1962 {target_copy => $copy->id, checkin_time => undef },
1963 { order_by => 'id DESC' }
1967 my $due_date = $circs->[0]->due_date;
1968 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1969 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1970 if (DateTime->compare($start_time, $due_date) < 0) {
1971 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1975 push @good_resources, $res;
1981 push @good_resources, $res if (isTrue($copy->status->holdable));
1984 # let 'em know we're still working
1985 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1987 # if we have no copies ...
1988 if (!@good_resources) {
1989 $log->info("\tNo resources available for targeting at all!\n");
1990 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1993 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1997 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1999 # LFW: note that after the inclusion of hold proximity
2000 # adjustment, this prox_list is the only prox_list
2001 # array in this perl package. Other occurences are
2007 $_->owner == $bresv->pickup_lib
2011 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
2012 # $all_copies is now a list of copies not at the pickup library
2014 my $best = shift @good_resources;
2015 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2018 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
2022 sort { $a->[0] <=> $b->[0] }
2024 [ actor::org_unit_proximity->search_where(
2025 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
2031 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2033 $best = shift @$prox_list
2037 $bresv->update( { current_resource => ''.$best->id } );
2038 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
2041 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2042 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
2045 { reservation => $bresv->id,
2046 current_resource => ($best ? $best->id : undef) };
2051 $log->error("Processing of bresv failed: $e");
2052 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
2053 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
2060 __PACKAGE__->register_method(
2061 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
2063 method => 'reservation_targeter',
2068 my %cache = (titles => {}, cns => {});
2070 sub copy_hold_capture {
2075 if (!defined($cps)) {
2077 $cps = [ asset::copy->search( id => $hold->target ) ];
2078 } catch Error with {
2080 die "Could not retrieve initial volume list:\n\n$e\n";
2084 my @copies = grep { $_->holdable } @$cps;
2086 for (my $i = 0; $i < @$cps; $i++) {
2087 next unless $$cps[$i];
2089 my $cn = $cache{cns}{$copies[$i]->call_number};
2090 my $rec = $cache{titles}{$cn->record};
2091 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
2092 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
2093 $copies[$i] = undef if (
2095 !$self->{user_filter}->request(
2096 'open-ils.circ.permit_hold',
2097 $hold->to_fieldmapper, do {
2098 my $cp_fm = $copies[$i]->to_fieldmapper;
2099 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
2100 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
2101 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
2104 { title => $rec->to_fieldmapper,
2105 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
2106 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
2109 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
2112 @copies = grep { $_ } @copies;
2114 my $count = @copies;
2116 return unless ($count);
2118 action::hold_copy_map->search( hold => $hold->id )->delete_all;
2121 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
2122 for my $c (@copies) {
2123 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
2125 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
2131 sub choose_nearest_copy {
2133 my $prox_list = shift;
2135 for my $p ( sort keys %$prox_list ) {
2136 next unless (ref $$prox_list{$p});
2138 my @capturable = @{ $$prox_list{$p} };
2139 next unless (@capturable);
2141 my $rand = int(rand(scalar(@capturable)));
2143 while (my ($c) = splice(@capturable, $rand, 1)) {
2144 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
2145 { title => $c->call_number->record->to_fieldmapper,
2146 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
2147 patron => $hold->usr->to_fieldmapper,
2148 copy => $c->to_fieldmapper,
2149 requestor => $hold->requestor->to_fieldmapper,
2150 request_lib => $hold->request_lib->to_fieldmapper,
2151 pickup_lib => $hold->pickup_lib->id,
2157 last unless(@capturable);
2158 $rand = int(rand(scalar(@capturable)));
2163 sub create_prox_list {
2169 my $actor = OpenSRF::AppSession->create('open-ils.actor');
2172 for my $cp (@$copies) {
2173 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib, $hold );
2174 next unless (defined($prox));
2176 my $copy_circ_lib = ''.$cp->circ_lib;
2177 # Fetch the weighting value for hold targeting, defaulting to 1
2178 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
2179 'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
2181 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
2182 $self->{target_weight}{$copy_circ_lib} ||= 1;
2184 $prox_list{$prox} = [] unless defined($prox_list{$prox});
2185 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
2186 push @{$prox_list{$prox}}, $cp;
2192 sub volume_hold_capture {
2197 if (!defined($vols)) {
2199 $vols = [ asset::call_number->search( id => $hold->target ) ];
2200 $cache{cns}{$_->id} = $_ for (@$vols);
2201 } catch Error with {
2203 die "Could not retrieve initial volume list:\n\n$e\n";
2207 my @v_ids = map { $_->id } @$vols;
2211 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
2213 } catch Error with {
2215 warn "Could not retrieve copy list:\n\n$e\n";
2218 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
2221 sub title_hold_capture {
2226 if (!defined($titles)) {
2228 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
2229 $cache{titles}{$_->id} = $_ for (@$titles);
2230 } catch Error with {
2232 die "Could not retrieve initial title list:\n\n$e\n";
2236 my @t_ids = map { $_->id } @$titles;
2239 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
2241 } catch Error with {
2243 warn "Could not retrieve volume list:\n\n$e\n";
2246 $cache{cns}{$_->id} = $_ for (@$cn_list);
2248 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
2251 sub metarecord_hold_capture {
2257 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
2259 } catch Error with {
2261 die "Could not retrieve initial title list:\n\n$e\n";
2265 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
2267 $titles = [ biblio::record_entry->search( id => \@recs ) ];
2269 } catch Error with {
2271 die "Could not retrieve format-pruned title list:\n\n$e\n";
2275 $cache{titles}{$_->id} = $_ for (@$titles);
2276 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);