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(). See the hash %order_by_sprintf_args in
21 # that sub to confirm what gets used to replace the formatters, and see
22 # nearest_hold() for the main body of the SQL query that these go into.
23 my %HOLD_SORT_ORDER_BY = (
25 hprox => 'actor.org_unit_proximity(%d, h.pickup_lib)', # $cp->call_number->owning_lib
26 aprox => 'COALESCE(hm.proximity, p.prox)',
27 approx => 'action.hold_copy_calculated_proximity(h.id, %d, %d)', # $cp,$here
28 priority => 'pgt.hold_priority',
29 cut => 'CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END',
30 depth => 'h.selection_depth',
31 rtime => 'h.request_time',
34 last_event_on_copy.place <> %d AND
35 copy_has_not_been_home.result
36 THEN actor.org_unit_proximity(%d, h.pickup_lib)
39 !, # $cp->call_number->owning_lib x 2
42 last_event_on_copy.place <> %d AND
43 copy_has_not_been_home_even_to_idle.result
44 THEN actor.org_unit_proximity(%d, h.pickup_lib)
47 !, # $cp->call_number->owning_lib x 2
53 return 1 if ($v == 1);
54 return 1 if ($v =~ /^t/io);
55 return 1 if ($v =~ /^y/io);
59 sub ou_ancestor_setting_value_or_cache {
60 # cache should be specific to setting
61 my ($actor, $org_id, $setting, $cache) = @_;
63 if (not exists $cache->{$org_id}) {
64 my $r = $actor->request(
65 'open-ils.actor.ou_setting.ancestor_default', $org_id, $setting
69 $cache->{$org_id} = $r->{value};
71 $cache->{$org_id} = undef;
74 return $cache->{$org_id};
77 my $parser = DateTime::Format::ISO8601->new;
78 my $log = 'OpenSRF::Utils::Logger';
80 sub open_noncat_circs {
85 my $a = action::non_cataloged_circulation->table;
86 my $c = config::non_cataloged_type->table;
91 JOIN $c c ON (a.item_type = c.id)
92 WHERE a.circ_time + c.circ_duration > current_timestamp
96 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
98 __PACKAGE__->register_method(
99 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
100 method => 'open_noncat_circs',
106 sub ou_hold_requests {
111 my $h_table = action::hold_request->table;
112 my $c_table = asset::copy->table;
113 my $o_table = actor::org_unit->table;
118 JOIN $c_table cp ON (cp.id = h.current_copy)
119 JOIN $o_table ou ON (ou.id = cp.circ_lib)
121 AND h.capture_time IS NULL
122 AND h.cancel_time IS NULL
123 AND (h.expire_time IS NULL OR h.expire_time > NOW())
124 ORDER BY h.request_time
127 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
130 $client->respond($_) for (
133 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
137 } @{ $sth->fetchall_arrayref }
141 __PACKAGE__->register_method(
142 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
146 method => 'ou_hold_requests',
151 my $upper_interval = shift || '1 millennium';
154 my $c_t = action::circulation->table;
159 WHERE stop_fines IS NULL
160 AND due_date < ( CURRENT_TIMESTAMP - grace_period )
161 AND fine_interval < ?::INTERVAL
164 my $sth = action::circulation->db_Main->prepare_cached($sql);
165 $sth->execute($upper_interval);
167 my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
169 $c_t = booking::reservation->table;
173 WHERE return_time IS NULL
174 AND end_time < ( CURRENT_TIMESTAMP )
175 AND fine_interval IS NOT NULL
176 AND cancel_time IS NULL
179 $sth = action::circulation->db_Main->prepare_cached($sql);
182 push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
187 sub complete_reshelving {
192 local $OpenILS::Application::Storage::WRITE = 1;
194 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
195 unless (interval_to_seconds( $window ));
197 my $cp = asset::copy->table;
206 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)
209 my $sth = action::circulation->db_Main->prepare_cached($sql);
210 $sth->execute($window);
215 __PACKAGE__->register_method(
216 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
219 method => 'complete_reshelving',
222 sub mark_longoverdue {
227 local $OpenILS::Application::Storage::WRITE = 1;
229 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
230 unless (interval_to_seconds( $window ));
232 my $setting = actor::org_unit_setting->table;
233 my $circ = action::circulation->table;
237 SET stop_fines = 'LONGOVERDUE',
238 stop_fines_time = now()
242 LEFT JOIN $setting setting
243 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
244 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
245 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
249 my $sth = action::circulation->db_Main->prepare_cached($sql);
250 $sth->execute($window);
255 __PACKAGE__->register_method(
256 api_name => 'open-ils.storage.action.circulation.long_overdue',
259 method => 'mark_longoverdue',
262 sub auto_thaw_frozen_holds {
266 local $OpenILS::Application::Storage::WRITE = 1;
268 my $holds = action::hold_request->table;
270 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
272 my $sth = action::hold_request->db_Main->prepare_cached($sql);
278 __PACKAGE__->register_method(
279 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
283 method => 'auto_thaw_frozen_holds',
290 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
292 $client->respond( $idlist ? $_ : $_->to_fieldmapper ) for ( overdue_circs('', $idlist) );
297 __PACKAGE__->register_method(
298 api_name => 'open-ils.storage.action.circulation.overdue',
301 method => 'grab_overdue',
303 Return list of overdue circulations and reservations to be used for fine generation.
304 Despite the name, this is not a generic method for retrieving all overdue loans,
305 as it excludes loans that have already hit the maximum fine limit.
308 __PACKAGE__->register_method(
309 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
312 method => 'grab_overdue',
315 sub get_hold_sort_order {
318 my $dbh = action::hold_request->db_Main;
320 # The purpose of this function is to return column names in a DB-configured
321 # order, so it won't do to add columns here or change column names unless
322 # you also change the expectation of anything calling this function.
324 my $row = $dbh->selectrow_hashref(
327 cbho.pprox, cbho.hprox, cbho.aprox, cbho.approx, cbho.priority,
328 cbho.cut, cbho.depth, cbho.htime, cbho.shtime, cbho.rtime
329 FROM config.best_hold_order cbho
331 SELECT oils_json_to_text(value)::INT
332 FROM actor.org_unit_ancestor_setting('circ.hold_capture_order', ?)
336 pprox => 1, hprox => 8, aprox => 2, priority => 3,
337 cut => 4, depth => 5, htime => 7, rtime => 6
340 # Return only the keys of our hash, sorted by value,
341 # keys for null values omitted.
343 grep { defined $row->{$_} } (
344 sort {$row->{$a} cmp $row->{$b}} keys %$row
349 # Returns an ORDER BY clause
350 # *and* a string with a CTE expression to precede the nearest-hold SQL query
351 # *and* a string with extra JOIN statements needed
352 sub build_hold_sort_clause {
353 my ($columns, $cp, $here) = @_;
355 my %order_by_sprintf_args = (
356 hprox => [$cp->call_number->owning_lib],
357 approx => [$cp->id, $here],
358 htime => [$cp->call_number->owning_lib, $cp->call_number->owning_lib],
359 shtime => [$cp->call_number->owning_lib, $cp->call_number->owning_lib]
364 foreach my $col (@$columns) {
365 if ($col eq 'htime' and not $ctes_needed) {
367 } elsif ($col eq 'shtime') {
372 @args = @{$order_by_sprintf_args{$col}} if
373 exists $order_by_sprintf_args{$col};
375 push @clauses, sprintf($HOLD_SORT_ORDER_BY{$col}, @args);
377 last if $col eq 'rtime'; # rtime is effectively unique, no need for
378 # more order-by clauses after that.
381 my ($ctes, $joins) = ("", "");
382 if ($ctes_needed >= 1) {
383 # Each CTE serves the next. The first is one version or another
384 # of last_event_on_copy, which is described in holds-go-home.txt
385 # TechRef, but it essentially returns place and time of the most
386 # recent transit or circ to do with a copy, and failing that it
387 # returns a synthetic event that means "here" and "now".
389 if ($ctes_needed == 2) {
391 , last_event_on_copy AS ( -- combined circ and transit version
397 COALESCE(dest_recv_time, source_send_time) AS moment
398 FROM action.transit_copy
399 WHERE target_copy = %d
400 ORDER BY moment DESC LIMIT 1
404 COALESCE(checkin_lib, circ_lib) AS place,
405 COALESCE(checkin_time, xact_start) AS moment
406 FROM action.circulation
407 WHERE target_copy = %d
408 ORDER BY moment DESC LIMIT 1
414 ) x ORDER BY concrete DESC, moment DESC LIMIT 1
415 ) !, $cp->id, $cp->id, $cp->call_number->owning_lib);
418 , last_event_on_copy AS ( -- circ only version
422 COALESCE(checkin_lib, circ_lib) AS place,
423 COALESCE(checkin_time, xact_start) AS moment
424 FROM action.circulation
425 WHERE target_copy = %d
426 ORDER BY moment DESC LIMIT 1
431 ) x ORDER BY concrete DESC, moment DESC LIMIT 1
432 ) !, $cp->id, $cp->call_number->owning_lib);
436 JOIN last_event_on_copy ON (true)
439 # For our next auxiliary query, the question we seek to answer is,
440 # "has our copy been circulating away from home too long?"
442 # Have there been no checkouts at the copy's circ_lib since the
443 # beginning of our go-home interval?
445 # [We use sprintf because the outer function that's going to send one
446 # big query through DBI is blind to our process of dynamically building
447 # these CTEs, and it wouldn't know what bind parameters to pass unless
448 # we did a lot more work here. This is injection-safe because we only
449 # use the %d formatter.]
451 , copy_has_not_been_home AS (
454 SELECT MIN(circ.id) FROM action.circulation circ
455 JOIN go_home_interval ON (true)
457 circ.target_copy = %d AND
458 circ.circ_lib = %d AND
459 circ.xact_start >= NOW() - go_home_interval.value
461 ) !, $cp->id, $cp->circ_lib);
464 JOIN copy_has_not_been_home ON (true)
468 if ($ctes_needed == 2) {
469 # By this query, we mean to determine that the copy hasn't landed at
470 # home by means of transit during the go-home interval (in addition
471 # to not having circulated from home in the same time frame).
473 # There have been no homebound transits that arrived for this copy
474 # since the beginning of the go-home interval.
477 , copy_has_not_been_home_even_to_idle AS (
478 SELECT result AND NOT (
479 SELECT COUNT(*)::INT::BOOL
480 FROM action.transit_copy atc
482 atc.target_copy = %d AND
483 (atc.dest = %d OR atc.source = %d) AND
484 atc.dest_recv_time >= NOW() - (SELECT value FROM go_home_interval)
485 ) AS result FROM copy_has_not_been_home
486 ) !, $cp->id, $cp->circ_lib, $cp->circ_lib);
487 $joins .= " JOIN copy_has_not_been_home_even_to_idle ON (true) ";
491 join(", ", @clauses),
500 my $here = shift; # just the ID
501 my $cp = shift; # now an object with call_number fleshed,
502 # formerly just copy ID
503 my $limit = int(shift()) || 10;
504 my $age = shift() || '0 seconds';
507 $log->info("deprecated 'fifo' param true, but ignored") if isTrue($fifo);
509 # ScriptBuilder fleshes the circ_lib, which confuses things; ensure we
510 # are working with a circ lib ID and not an object
512 if (ref $cp->circ_lib) {
513 $cp_circ_lib = $cp->circ_lib->id;
515 $cp_circ_lib = $cp->circ_lib;
519 if (ref $cp->call_number->owning_lib) {
520 $cp_owning_lib = $cp->call_number->owning_lib->id;
522 $cp_owning_lib = $cp->call_number->owning_lib;
525 my ($holdsort, $addl_cte, $addl_join) =
526 build_hold_sort_clause(get_hold_sort_order($cp_owning_lib), $cp, $here);
528 local $OpenILS::Application::Storage::WRITE = 1;
530 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $cp_circ_lib, $here, $cp->id, $age);
531 WITH go_home_interval AS (
532 SELECT OILS_JSON_TO_TEXT(
533 (SELECT value FROM actor.org_unit_ancestor_setting(
534 'circ.hold_go_home_interval', ?
536 ))::INTERVAL AS value
540 FROM action.hold_request h
541 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
542 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
543 JOIN actor.usr au ON (au.id = h.usr)
544 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
545 LEFT JOIN actor.usr_standing_penalty ausp
546 ON ( au.id = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
547 LEFT JOIN config.standing_penalty csp
548 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
550 WHERE hm.target_copy = ?
551 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR hm.proximity = 0 OR p.prox = 0)
552 AND h.capture_time IS NULL
553 AND h.cancel_time IS NULL
554 AND (h.expire_time IS NULL OR h.expire_time > NOW())
555 AND h.frozen IS FALSE
557 ORDER BY CASE WHEN h.hold_type IN ('R','F') THEN 0 ELSE 1 END, $holdsort
561 $client->respond( $_ ) for ( @$ids );
564 __PACKAGE__->register_method(
565 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
568 method => 'nearest_hold',
571 sub targetable_holds {
574 my $check_expire = shift;
576 $check_expire ||= '12h';
578 local $OpenILS::Application::Storage::WRITE = 1;
580 # json_query can *almost* represent this query, but can't
581 # handle the CASE statement or the interval arithmetic
582 my $query = <<" SQL";
583 SELECT ahr.id, mmsm.metarecord
584 FROM action.hold_request ahr
585 JOIN reporter.hold_request_record USING (id)
586 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
587 WHERE capture_time IS NULL
588 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
589 AND fulfillment_time IS NULL
590 AND cancel_time IS NULL
592 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
594 my $sth = action::hold_request->db_Main->prepare_cached($query);
595 $sth->execute($check_expire);
596 $client->respond( $_ ) for @{ $sth->fetchall_arrayref };
601 __PACKAGE__->register_method(
602 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
605 method => 'targetable_holds',
607 Returns ordered list of hold request and metarecord IDs
608 for all hold requests that are available for initial targeting
610 @param check interval
611 @return list of pairs of hold request and metarecord IDs
615 sub next_resp_group_id {
619 # XXX This is not replication safe!!!
621 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
622 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
626 __PACKAGE__->register_method(
627 api_name => 'open-ils.storage.action.survey_response.next_group_id',
629 method => 'next_resp_group_id',
632 sub patron_circ_summary {
637 return undef unless ($id);
638 my $c_table = action::circulation->table;
639 my $b_table = money::billing->table;
641 $log->debug("Retrieving patron summary for id $id", DEBUG);
643 my $select = <<" SQL";
644 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
646 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
648 AND c.xact_finish IS NULL
650 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
651 OR c.stop_fines IS NULL
655 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
657 __PACKAGE__->register_method(
658 api_name => 'open-ils.storage.action.circulation.patron_summary',
660 method => 'patron_circ_summary',
663 #XXX Fix stored proc calls
664 sub find_local_surveys {
669 return undef unless ($ou);
670 my $s_table = action::survey->table;
672 my $select = <<" SQL";
675 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
676 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
679 my $sth = action::survey->db_Main->prepare_cached($select);
682 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
686 __PACKAGE__->register_method(
687 api_name => 'open-ils.storage.action.survey.all',
690 method => 'find_local_surveys',
693 #XXX Fix stored proc calls
694 sub find_opac_surveys {
699 return undef unless ($ou);
700 my $s_table = action::survey->table;
702 my $select = <<" SQL";
705 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
706 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
710 my $sth = action::survey->db_Main->prepare_cached($select);
713 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
717 __PACKAGE__->register_method(
718 api_name => 'open-ils.storage.action.survey.opac',
721 method => 'find_opac_surveys',
728 my $limit = shift || 10;
729 my $offset = shift || 0;
731 return undef unless ($ou);
732 my $h_table = action::hold_request->table;
733 my $a_table = asset::copy->table;
734 my $ord_table = asset::copy_location_order->table;
736 my $idlist = 1 if ($self->api_name =~/id_list/o);
737 my $count = 1 if ($self->api_name =~/count$/o);
739 my $status_filter = '';
740 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
742 my $select = <<" SQL";
745 JOIN $a_table a ON (h.current_copy = a.id)
746 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
747 LEFT JOIN actor.usr_standing_penalty ausp
748 ON ( h.usr = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
749 LEFT JOIN config.standing_penalty csp
750 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
752 AND h.capture_time IS NULL
753 AND h.cancel_time IS NULL
754 AND (h.expire_time IS NULL OR h.expire_time > NOW())
757 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
766 JOIN $a_table a ON (h.current_copy = a.id)
767 LEFT JOIN actor.usr_standing_penalty ausp
768 ON ( h.usr = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
769 LEFT JOIN config.standing_penalty csp
770 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
772 AND h.capture_time IS NULL
773 AND h.cancel_time IS NULL
774 AND (h.expire_time IS NULL OR h.expire_time > NOW())
780 my $sth = action::survey->db_Main->prepare_cached($select);
784 $client->respond( $sth->fetchall_arrayref()->[0][0] );
786 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
788 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
793 __PACKAGE__->register_method(
794 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
798 "Returns a count of holds for a specific library's pull list.",
799 [ [org_unit => "The library's org id", "number"] ],
800 ['A count of holds for the stated library to pull ', 'number']
802 method => 'hold_pull_list',
804 __PACKAGE__->register_method(
805 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
809 "Returns a status filtered count of holds for a specific library's pull list.",
810 [ [org_unit => "The library's org id", "number"] ],
811 ['A status filtered count of holds for the stated library to pull ', 'number']
813 method => 'hold_pull_list',
815 __PACKAGE__->register_method(
816 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
820 "Returns the hold ids for a specific library's pull list.",
821 [ [org_unit => "The library's org id", "number"],
822 [limit => 'An optional page size, defaults to 10', 'number'],
823 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
825 ['A list of holds for the stated library to pull for', 'array']
827 method => 'hold_pull_list',
829 __PACKAGE__->register_method(
830 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
834 "Returns the holds for a specific library's pull list.",
835 [ [org_unit => "The library's org id", "number"],
836 [limit => 'An optional page size, defaults to 10', 'number'],
837 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
839 ['A list of holds for the stated library to pull for', 'array']
841 method => 'hold_pull_list',
843 __PACKAGE__->register_method(
844 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
848 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
849 [ [org_unit => "The library's org id", "number"],
850 [limit => 'An optional page size, defaults to 10', 'number'],
851 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
853 ['A list of holds for the stated library to pull for', 'array']
855 method => 'hold_pull_list',
857 __PACKAGE__->register_method(
858 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
862 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
863 [ [org_unit => "The library's org id", "number"],
864 [limit => 'An optional page size, defaults to 10', 'number'],
865 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
867 ['A list of holds for the stated library to pull for', 'array']
869 method => 'hold_pull_list',
872 sub find_optional_surveys {
877 return undef unless ($ou);
878 my $s_table = action::survey->table;
880 my $select = <<" SQL";
883 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
884 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
885 AND s.required IS FALSE;
888 my $sth = action::survey->db_Main->prepare_cached($select);
891 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
895 __PACKAGE__->register_method(
896 api_name => 'open-ils.storage.action.survey.optional',
899 method => 'find_optional_surveys',
902 sub find_required_surveys {
907 return undef unless ($ou);
908 my $s_table = action::survey->table;
910 my $select = <<" SQL";
913 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
914 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
915 AND s.required IS TRUE;
918 my $sth = action::survey->db_Main->prepare_cached($select);
921 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
925 __PACKAGE__->register_method(
926 api_name => 'open-ils.storage.action.survey.required',
929 method => 'find_required_surveys',
932 sub find_usr_summary_surveys {
937 return undef unless ($ou);
938 my $s_table = action::survey->table;
940 my $select = <<" SQL";
943 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
944 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
945 AND s.usr_summary IS TRUE;
948 my $sth = action::survey->db_Main->prepare_cached($select);
951 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
955 __PACKAGE__->register_method(
956 api_name => 'open-ils.storage.action.survey.usr_summary',
959 method => 'find_usr_summary_surveys',
962 sub seconds_to_interval_hash {
963 my $interval = shift;
964 my $limit = shift || 's';
965 $limit =~ s/^(.)/$1/o;
969 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
970 my ($year, $month, $week, $day, $hour, $minute, $second) =
971 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
973 if ($y = int($interval / (60 * 60 * 24 * 365))) {
975 $ym = $interval % (60 * 60 * 24 * 365);
979 return %output if ($limit eq 'y');
981 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
982 $output{$month} = $M;
983 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
987 return %output if ($limit eq 'M');
989 if ($w = int($Mm / 604800)) {
995 return %output if ($limit eq 'w');
997 if ($d = int($wm / 86400)) {
1003 return %output if ($limit eq 'd');
1005 if ($h = int($dm / 3600)) {
1006 $output{$hour} = $h;
1011 return %output if ($limit eq 'h');
1013 if ($m = int($hm / 60)) {
1014 $output{$minute} = $m;
1019 return %output if ($limit eq 'm');
1021 if ($s = int($mm)) {
1022 $output{$second} = $s;
1024 $output{$second} = 0 unless (keys %output);
1030 sub generate_fines {
1034 my $overbill = shift;
1036 local $OpenILS::Application::Storage::WRITE = 1;
1041 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
1042 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
1044 push @circs, overdue_circs();
1047 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
1049 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
1050 for my $c (@circs) {
1052 my $ctype = ref($c);
1053 $ctype =~ s/^.+::(\w+)$/$1/;
1055 my $due_date_method = 'due_date';
1056 my $target_copy_method = 'target_copy';
1057 my $circ_lib_method = 'circ_lib';
1058 my $recurring_fine_method = 'recurring_fine';
1059 my $is_reservation = 0;
1060 if ($ctype eq 'reservation') {
1061 $is_reservation = 1;
1062 $due_date_method = 'end_time';
1063 $target_copy_method = 'current_resource';
1064 $circ_lib_method = 'pickup_lib';
1065 $recurring_fine_method = 'fine_amount';
1066 next unless ($c->fine_interval);
1068 #TODO: reservation grace periods
1069 my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
1072 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1073 $log->debug("Cleaning up after previous transaction\n");
1074 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1076 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1078 sprintf("Processing %s %d...",
1079 ($is_reservation ? "reservation" : "circ"), $c->id
1084 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
1086 my $due = $due_dt->epoch;
1089 my $fine_interval = $c->fine_interval;
1090 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
1091 $fine_interval = interval_to_seconds( $fine_interval );
1093 if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
1094 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
1095 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
1099 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
1100 my $tz_offset_s = 0;
1101 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
1102 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
1105 $due -= ($due % $fine_interval) + $tz_offset_s;
1106 $now -= ($now % $fine_interval) + $tz_offset_s;
1110 "ARG! Overdue $ctype ".$c->id.
1111 " for item ".$c->$target_copy_method.
1112 " (user ".$c->usr.").\n".
1113 "\tItem was due on or before: ".localtime($due)."\n");
1115 my @fines = money::billing->search_where(
1118 billing_ts => { '>' => $c->$due_date_method } },
1119 { order_by => 'billing_ts DESC'}
1123 my $fine = $fines[$f_idx] if (@fines);
1125 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
1128 my $current_fine_total = 0;
1129 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
1133 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
1134 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
1136 $log->info( "Potential first billing for circ ".$c->id );
1139 $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});
1142 return if ($last_fine > $now);
1143 # Generate fines for each past interval, including the one we are inside
1144 my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
1146 if ( $last_fine == $due # we have no fines yet
1147 && $grace_period # and we have a grace period
1148 && $now < $due + $grace_period # and some date math says were are within the grace period
1150 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
1151 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
1155 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
1156 return unless ($pending_fine_count);
1158 my $recurring_fine = int($c->$recurring_fine_method * 100);
1159 my $max_fine = int($c->max_fine * 100);
1161 my $skip_closed_check = $U->ou_ancestor_setting_value(
1162 $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.charge_when_closed');
1163 $skip_closed_check = $U->is_true($skip_closed_check);
1165 my $truncate_to_max_fine = $U->ou_ancestor_setting_value(
1166 $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.truncate_to_max_fine');
1167 $truncate_to_max_fine = $U->is_true($truncate_to_max_fine);
1169 my ($latest_billing_ts, $latest_amount) = ('',0);
1170 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
1172 if ($current_fine_total >= $max_fine) {
1173 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
1175 "\tMaximum fine level of ".$c->max_fine.
1176 " reached for this $ctype.\n".
1177 "\tNo more fines will be generated.\n" );
1181 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
1182 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
1183 my $current_bill_count = $bill;
1184 while ( $current_bill_count ) {
1185 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
1186 $current_bill_count--;
1189 my $timestamptz = $billing_ts->strftime('%FT%T%z');
1190 if (!$skip_closed_check) {
1191 my $dow = $billing_ts->day_of_week_0();
1192 my $dow_open = "dow_${dow}_open";
1193 my $dow_close = "dow_${dow}_close";
1195 if (my $h = $hoo{$c->$circ_lib_method}) {
1196 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
1199 my @cl = actor::org_unit::closed_date->search_where(
1200 { close_start => { '<=' => $timestamptz },
1201 close_end => { '>=' => $timestamptz },
1202 org_unit => $c->$circ_lib_method }
1207 # The billing amount for this billing normally ought to be the recurring fine amount.
1208 # However, if the recurring fine amount would cause total fines to exceed the max fine amount,
1209 # we may wish to reduce the amount for this billing (if circ.fines.truncate_to_max_fine is true).
1210 my $this_billing_amount = $recurring_fine;
1211 if ( $truncate_to_max_fine && ($current_fine_total + $this_billing_amount) > $max_fine ) {
1212 $this_billing_amount = ($max_fine - $current_fine_total);
1214 $current_fine_total += $this_billing_amount;
1215 $latest_amount += $this_billing_amount;
1216 $latest_billing_ts = $timestamptz;
1218 money::billing->create(
1219 { xact => ''.$c->id,
1220 note => "System Generated Overdue Fine",
1221 billing_type => "Overdue materials",
1223 amount => sprintf('%0.2f', $this_billing_amount/100),
1224 billing_ts => $timestamptz,
1230 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
1231 if ($latest_billing_ts and $latest_amount);
1233 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1237 # Caluclate penalties inline
1238 OpenILS::Utils::Penalty->calculate_penalties(
1239 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
1243 # Calculate penalties with an aysnc call to the penalty server. This approach
1244 # may lead to duplicate penalties since multiple penalty processes for a
1245 # given user may be running at the same time. Leave this here for reference
1246 # in case we later find that asyc calls are needed in some environments.
1248 'open-ils.penalty.patron_penalty.calculate',
1249 { patronid => ''.$c->usr,
1250 context_org => ''.$c->$circ_lib_method,
1261 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
1262 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
1263 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1264 last if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1268 __PACKAGE__->register_method(
1269 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1272 method => 'generate_fines',
1277 sub new_hold_copy_targeter {
1280 my $check_expire = shift;
1281 my $one_hold = shift;
1282 my $find_copy = shift;
1284 local $OpenILS::Application::Storage::WRITE = 1;
1286 $self->{target_weight} = {};
1287 $self->{max_loops} = {};
1293 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1294 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
1295 } elsif ( $check_expire ) {
1297 # what's the retarget time threashold?
1299 $check_expire ||= '12h';
1300 $check_expire = interval_to_seconds( $check_expire );
1302 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1305 my $expire_threshold = sprintf(
1306 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1307 $year, $mon, $mday, $hour, $min, $sec
1310 # find all the holds holds needing retargeting
1311 $holds = [ action::hold_request->search_where(
1312 { capture_time => undef,
1313 fulfillment_time => undef,
1314 cancel_time => undef,
1316 prev_check_time => { '<=' => $expire_threshold },
1318 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
1320 # find all the holds holds needing first time targeting
1321 push @$holds, action::hold_request->search(
1322 capture_time => undef,
1323 fulfillment_time => undef,
1324 prev_check_time => undef,
1326 cancel_time => undef,
1327 { order_by => 'selection_depth DESC, request_time' } );
1330 # find all the holds holds needing first time targeting ONLY
1331 $holds = [ action::hold_request->search(
1332 capture_time => undef,
1333 fulfillment_time => undef,
1334 prev_check_time => undef,
1335 cancel_time => undef,
1337 { order_by => 'selection_depth DESC, request_time' } ) ];
1339 } catch Error with {
1341 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1344 my @closed = actor::org_unit::closed_date->search_where(
1345 { close_start => { '<=', 'now' },
1346 close_end => { '>=', 'now' } }
1349 if ($check_expire) {
1351 # $check_expire, if it exists, was already converted to seconds
1352 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1356 my $next_check_time = sprintf(
1357 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1358 $year, $mon, $mday, $hour, $min, $sec
1362 my @closed_at_next = actor::org_unit::closed_date->search_where(
1363 { close_start => { '<=', $next_check_time },
1364 close_end => { '>=', $next_check_time } }
1368 for my $c_at_n (@closed_at_next) {
1369 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1370 push @new_closed, $c_at_n;
1373 @closed = @new_closed;
1377 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1379 my $target_when_closed = {};
1380 my $target_when_closed_if_at_pickup_lib = {};
1382 for my $hold (@$holds) {
1384 #start a transaction if needed
1385 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1386 $log->debug("Cleaning up after previous transaction\n");
1387 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1389 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1390 $log->info("Processing hold ".$hold->id."...\n");
1392 #first, re-fetch the hold, to make sure it's not captured already
1393 $hold->remove_from_object_index();
1394 $hold = action::hold_request->retrieve( $hold->id );
1396 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1398 # remove old auto-targeting maps
1399 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1400 $_->delete for (@oldmaps);
1402 if ($hold->expire_time) {
1403 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1404 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1406 # cancel cause = un-targeted expiration
1407 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1409 # refresh fields from the DB while still in the xact
1410 my $fm_hold = $hold->to_fieldmapper;
1412 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1414 # tell A/T the hold was cancelled
1415 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1416 $ses->request('open-ils.trigger.event.autocreate',
1417 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1423 my $all_copies = [];
1425 # find filters for MR holds
1426 my ($types, $formats, $lang);
1427 if (defined($hold->holdable_formats)) {
1428 ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1431 # find all the potential copies
1432 if ($hold->hold_type eq 'M') {
1435 isTrue($_->deleted) ? () : ($_->id)
1436 } metabib::metarecord->retrieve($hold->target)->source_records
1441 metabib::record_descriptor
1444 ( $types ? (item_type => [split '', $types]) : () ),
1445 ( $formats ? (item_form => [split '', $formats]) : () ),
1446 ( $lang ? (item_lang => $lang) : () ),
1450 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1451 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1453 for my $cn ( @{ $rtree->call_numbers } ) {
1455 asset::copy->search_where(
1456 { id => [map {$_->id} @{ $cn->copies }],
1458 ) if ($cn && @{ $cn->copies });
1462 } elsif ($hold->hold_type eq 'T') {
1464 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1465 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1468 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1472 for my $cn ( @{ $rtree->call_numbers } ) {
1474 asset::copy->search_where(
1475 { id => [map {$_->id} @{ $cn->copies }],
1477 ) if ($cn && @{ $cn->copies });
1479 } elsif ($hold->hold_type eq 'V') {
1481 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1482 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1485 asset::copy->search_where(
1486 { id => [map {$_->id} @{ $vtree->copies }],
1488 ) if ($vtree && @{ $vtree->copies });
1490 } elsif ($hold->hold_type eq 'P') {
1491 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1493 asset::copy->search_where(
1494 { id => [map {$_->target_copy} @part_maps],
1499 } elsif ($hold->hold_type eq 'I') {
1501 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1502 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1505 asset::copy->search_where(
1506 { id => [map {$_->unit->id} @{ $itree->items }],
1508 ) if ($itree && @{ $itree->items });
1510 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1511 my $_cp = asset::copy->retrieve($hold->target);
1512 push @$all_copies, $_cp if $_cp;
1515 # Force and recall holds bypass pretty much everything
1516 if ($hold->hold_type ne 'R' && $hold->hold_type ne 'F') {
1518 @$all_copies = grep { isTrue($_->status->holdable) &&
1519 isTrue($_->location->holdable) &&
1520 isTrue($_->holdable) &&
1521 !isTrue($_->deleted) &&
1522 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1523 ( ( $hold->hold_type ne 'C' && $hold->hold_type ne 'I' # Copy-level holds don't care about parts
1524 && $hold->hold_type ne 'P' ) ? $_->part_maps->count == 0 : 1)
1528 # let 'em know we're still working
1529 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1531 # if we have no copies ...
1532 if (!ref $all_copies || !@$all_copies) {
1533 $log->info("\tNo copies available for targeting at all!\n");
1534 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1536 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1537 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1541 my $copy_count = @$all_copies;
1542 my $found_copy = undef;
1543 $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1545 # map the potentials, so that we can pick up checkins
1546 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1547 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1548 my $pu_lib = ''.$hold->pickup_lib;
1549 my $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold );
1550 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1551 for my $prox ( keys %$prox_list ) {
1552 action::hold_copy_map->create( { proximity => $prox, hold => $hold->id, target_copy => $_ } )
1553 for keys( %{{ map { $_->id => 1 } @{$$prox_list{$prox}} }} );
1556 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1559 for my $c (@$all_copies) {
1561 next if ($hold->current_copy and $c->id eq $hold->current_copy);
1563 # skip on circ lib is closed IFF we care
1566 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1567 $ignore_closing = ou_ancestor_setting_value_or_cache(
1570 'circ.holds.target_when_closed_if_at_pickup_lib',
1571 $target_when_closed_if_at_pickup_lib
1574 if (not $ignore_closing) { # one more chance to find a reason
1575 # to ignore OU closedness.
1576 $ignore_closing = ou_ancestor_setting_value_or_cache(
1579 'circ.holds.target_when_closed',
1585 # "For hold " . $hold->id . " and copy with circ_lib " .
1586 # $c->circ_lib . " we " .
1587 # ($ignore_closing ? "ignore" : "respect")
1592 (not $ignore_closing) and
1593 (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1596 # target of another hold
1597 next if (action::hold_request
1599 { current_copy => $c->id,
1600 fulfillment_time => undef,
1601 cancel_time => undef,
1606 # we passed all three, keep it
1607 push @good_copies, $c if ($c);
1608 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1611 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1613 my $old_best = $hold->current_copy;
1614 my $old_best_still_valid = 0; # Assume no, but the next line says yes if it is still a potential.
1615 $old_best_still_valid = 1 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies );
1616 $hold->update({ current_copy => undef }) if ($old_best);
1618 if (!scalar(@good_copies)) {
1619 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1620 if ( $old_best_still_valid ) {
1621 # the old copy is still available
1622 $log->debug("\tPushing current_copy back onto the targeting list");
1623 push @good_copies, $old_best;
1625 # oops, old copy is not available
1626 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1627 $hold->update( { prev_check_time => 'today' } );
1628 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1629 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1634 # reset prox list after trimming good copies
1635 $prox_list = create_prox_list(
1637 [ grep { $_->status == 0 || $_->status == 7 } @good_copies ],
1641 $all_copies = [ grep { ''.$_->circ_lib ne $pu_lib && ( $_->status == 0 || $_->status == 7 ) } @good_copies ];
1643 my $min_prox = [ sort keys %$prox_list ]->[0];
1645 if ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') { # Recall/Force holds bypass hold rules.
1646 $best = $good_copies[0] if(scalar @good_copies);
1648 $best = choose_nearest_copy($hold, { $min_prox => delete($$prox_list{$min_prox}) });
1651 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1654 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1656 $self->{max_loops}{$pu_lib} = $actor->request(
1657 'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1660 if (defined($self->{max_loops}{$pu_lib})) {
1661 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1663 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1664 my $circ_lib_list = [keys %circ_lib_map];
1666 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1668 # Grab the "biggest" loop for this hold so far
1669 my $current_loop = $cstore->request(
1670 'open-ils.cstore.json_query',
1672 select => { aufhmxl => ['max'] },
1674 where => { hold => $hold->id}
1678 $current_loop = $current_loop->{max} if ($current_loop);
1679 $current_loop ||= 1;
1681 my $exclude_list = $cstore->request(
1682 'open-ils.cstore.json_query.atomic',
1684 select => { aufhol => ['circ_lib'] },
1686 where => { hold => $hold->id}
1691 if ($exclude_list && @$exclude_list) {
1692 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1693 # check to see if we've used up every library in the potentials list
1694 for my $l ( @$circ_lib_list ) {
1696 for my $ex ( @$exclude_list ) {
1702 push(@keepers, $l) if ($keep);
1705 @keepers = @$circ_lib_list;
1708 $current_loop++ if (!@keepers);
1710 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1711 # We haven't exceeded max_loops yet
1713 for my $cp ( @$all_copies ) {
1714 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1717 $all_copies = [@keeper_copies];
1719 # We have, and should remove potentials and cancel the hold
1720 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1721 $_->delete for (@oldmaps);
1723 # cancel cause = un-targeted expiration
1724 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1726 # refresh fields from the DB while still in the xact
1727 my $fm_hold = $hold->to_fieldmapper;
1729 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1731 # tell A/T the hold was cancelled
1732 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1733 $ses->request('open-ils.trigger.event.autocreate',
1734 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1739 $prox_list = create_prox_list( $self, $pu_lib, $all_copies, $hold );
1741 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1745 $best = choose_nearest_copy($hold, $prox_list);
1748 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1750 # hold wasn't fulfilled, record the fact
1752 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1753 action::unfulfilled_hold_list->create(
1754 { hold => ''.$hold->id,
1755 current_copy => ''.$old_best->id,
1756 circ_lib => ''.$old_best->circ_lib,
1761 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1762 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1764 $old_best_still_valid &&
1765 !action::hold_request
1767 { current_copy => $old_best->id,
1768 fulfillment_time => undef,
1769 cancel_time => undef,
1772 ( OpenILS::Utils::PermitHold::permit_copy_hold(
1773 { title => $old_best->call_number->record->to_fieldmapper,
1774 title_descriptor => $old_best->call_number->record->record_descriptor->next->to_fieldmapper,
1775 patron => $hold->usr->to_fieldmapper,
1776 copy => $old_best->to_fieldmapper,
1777 requestor => $hold->requestor->to_fieldmapper,
1778 request_lib => $hold->request_lib->to_fieldmapper,
1779 pickup_lib => $hold->pickup_lib->id,
1784 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1785 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1787 $hold->update( { prev_check_time => 'now' } );
1788 $log->info( "\tThere were no targetable copies for the hold" );
1789 process_recall($actor, $log, $hold, \@good_copies);
1792 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1793 $log->info("\tProcessing of hold ".$hold->id." complete.");
1796 { hold => $hold->id,
1797 old_target => ($old_best ? $old_best->id : undef),
1798 eligible_copies => $copy_count,
1799 target => ($best ? $best->id : undef),
1800 found_copy => $found_copy };
1805 $log->error("Processing of hold failed: $e");
1806 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1807 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1814 __PACKAGE__->register_method(
1815 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1817 method => 'new_hold_copy_targeter',
1820 sub process_recall {
1821 my ($actor, $log, $hold, $good_copies) = @_;
1823 # Bail early if we don't have required settings to avoid spurious requests
1824 my ($recall_threshold, $return_interval, $fine_rules);
1826 my $rv = $actor->request(
1827 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1831 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1834 $recall_threshold = $rv->{value};
1836 $rv = $actor->request(
1837 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1841 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1844 $return_interval = $rv->{value};
1846 $rv = $actor->request(
1847 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1851 $fine_rules = $rv->{value};
1854 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1856 # We want checked out copies (status = 1) at the hold pickup lib
1857 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1859 my @copy_ids = map { $_->id } @$all_copies;
1861 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1863 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1865 # Iterate over the checked-out copies to find a copy with a
1866 # loan period longer than the recall threshold:
1867 my $circs = [ action::circulation->search_where(
1868 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1869 { order_by => 'due_date ASC' }
1872 # If we have a candidate copy, then:
1873 if (scalar(@$circs)) {
1874 my $circ = $circs->[0];
1875 $log->info("Recalling circ ID : " . $circ->id);
1877 # Give the user a new due date of either a full recall threshold,
1878 # or the return interval, whichever is further in the future
1879 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1880 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1881 $return_date = $threshold_date;
1884 my $update_fields = {
1885 due_date => $return_date,
1886 renewal_remaining => 0,
1889 # If the OU hasn't defined new fine rules for recalls, keep them
1892 $log->info("Apply recall fine rules: $fine_rules");
1893 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1894 $update_fields->{recurring_fine} = $rules->[0];
1895 $update_fields->{fine_interval} = $rules->[1];
1896 $update_fields->{max_fine} = $rules->[2];
1899 # Adjust circ for current user
1900 $circ->update($update_fields);
1902 # Create trigger event for notifying current user
1903 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1904 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1907 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1910 sub reservation_targeter {
1913 my $one_reservation = shift;
1915 local $OpenILS::Application::Storage::WRITE = 1;
1920 if ($one_reservation) {
1921 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1922 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1925 # find all the reservations needing targeting
1927 booking::reservation->search_where(
1928 { current_resource => undef,
1929 cancel_time => undef,
1930 start_time => { '>' => 'now' }
1932 { order_by => 'start_time' }
1936 } catch Error with {
1938 die "Could not retrieve reservation requests:\n\n$e\n";
1942 for my $bresv (@$reservations) {
1944 #start a transaction if needed
1945 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1946 $log->debug("Cleaning up after previous transaction\n");
1947 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1949 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1950 $log->info("Processing reservation ".$bresv->id."...\n");
1952 #first, re-fetch the hold, to make sure it's not captured already
1953 $bresv->remove_from_object_index();
1954 $bresv = booking::reservation->retrieve( $bresv->id );
1956 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1958 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1959 if (DateTime->compare($end_time, DateTime->now) < 0) {
1961 # cancel cause = un-targeted expiration
1962 $bresv->update( { cancel_time => 'now' } );
1964 # refresh fields from the DB while still in the xact
1965 my $fm_bresv = $bresv->to_fieldmapper;
1967 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1969 # tell A/T the reservation was cancelled
1970 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1971 $ses->request('open-ils.trigger.event.autocreate',
1972 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1977 my $possible_resources;
1979 # find all the potential resources
1980 if (!$bresv->target_resource) {
1981 my $filter = { type => $bresv->target_resource_type };
1982 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1984 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1986 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1987 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1988 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1990 $possible_resources = $bresv->target_resource;
1993 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1994 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1997 my @good_resources = ();
1999 for my $res (@$all_resources) {
2000 unless (isTrue($res->type->catalog_item)) {
2001 push @good_resources, $res;
2005 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
2008 push @good_resources, $res;
2012 # At this point, if we're just targeting one specific
2013 # resource, just succeed. We don't care about its present
2015 if ($bresv->target_resource) {
2016 push @good_resources, $res;
2020 if ($copy->status->id == 0 || $copy->status->id == 7) {
2021 push @good_resources, $res;
2025 if ($copy->status->id == 1) {
2026 my $circs = [ action::circulation->search_where(
2027 {target_copy => $copy->id, checkin_time => undef },
2028 { order_by => 'id DESC' }
2032 my $due_date = $circs->[0]->due_date;
2033 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
2034 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
2035 if (DateTime->compare($start_time, $due_date) < 0) {
2036 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
2040 push @good_resources, $res;
2046 push @good_resources, $res if (isTrue($copy->status->holdable));
2049 # let 'em know we're still working
2050 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2052 # if we have no copies ...
2053 if (!@good_resources) {
2054 $log->info("\tNo resources available for targeting at all!\n");
2055 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
2058 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2062 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
2064 # LFW: note that after the inclusion of hold proximity
2065 # adjustment, this prox_list is the only prox_list
2066 # array in this perl package. Other occurences are
2072 $_->owner == $bresv->pickup_lib
2076 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
2077 # $all_copies is now a list of copies not at the pickup library
2079 my $best = shift @good_resources;
2080 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2083 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
2087 sort { $a->[0] <=> $b->[0] }
2089 [ actor::org_unit_proximity->search_where(
2090 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
2096 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
2098 $best = shift @$prox_list
2102 $bresv->update( { current_resource => ''.$best->id } );
2103 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
2106 $self->method_lookup('open-ils.storage.transaction.commit')->run;
2107 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
2110 { reservation => $bresv->id,
2111 current_resource => ($best ? $best->id : undef) };
2116 $log->error("Processing of bresv failed: $e");
2117 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
2118 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
2125 __PACKAGE__->register_method(
2126 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
2128 method => 'reservation_targeter',
2133 my %cache = (titles => {}, cns => {});
2135 sub copy_hold_capture {
2140 if (!defined($cps)) {
2142 $cps = [ asset::copy->search( id => $hold->target ) ];
2143 } catch Error with {
2145 die "Could not retrieve initial volume list:\n\n$e\n";
2149 my @copies = grep { $_->holdable } @$cps;
2151 for (my $i = 0; $i < @$cps; $i++) {
2152 next unless $$cps[$i];
2154 my $cn = $cache{cns}{$copies[$i]->call_number};
2155 my $rec = $cache{titles}{$cn->record};
2156 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
2157 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
2158 $copies[$i] = undef if (
2160 !$self->{user_filter}->request(
2161 'open-ils.circ.permit_hold',
2162 $hold->to_fieldmapper, do {
2163 my $cp_fm = $copies[$i]->to_fieldmapper;
2164 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
2165 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
2166 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
2169 { title => $rec->to_fieldmapper,
2170 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
2171 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
2174 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
2177 @copies = grep { $_ } @copies;
2179 my $count = @copies;
2181 return unless ($count);
2183 action::hold_copy_map->search( hold => $hold->id )->delete_all;
2186 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
2187 for my $c (@copies) {
2188 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
2190 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
2196 sub choose_nearest_copy {
2198 my $prox_list = shift;
2200 for my $p ( sort keys %$prox_list ) {
2201 next unless (ref $$prox_list{$p});
2203 my @capturable = @{ $$prox_list{$p} };
2204 next unless (@capturable);
2206 my $rand = int(rand(scalar(@capturable)));
2208 while (my ($c) = splice(@capturable, $rand, 1)) {
2209 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
2210 { title => $c->call_number->record->to_fieldmapper,
2211 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
2212 patron => $hold->usr->to_fieldmapper,
2213 copy => $c->to_fieldmapper,
2214 requestor => $hold->requestor->to_fieldmapper,
2215 request_lib => $hold->request_lib->to_fieldmapper,
2216 pickup_lib => $hold->pickup_lib->id,
2222 last unless(@capturable);
2223 $rand = int(rand(scalar(@capturable)));
2228 sub create_prox_list {
2234 my $actor = OpenSRF::AppSession->create('open-ils.actor');
2237 for my $cp (@$copies) {
2238 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib, $hold );
2239 next unless (defined($prox));
2241 my $copy_circ_lib = ''.$cp->circ_lib;
2242 # Fetch the weighting value for hold targeting, defaulting to 1
2243 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
2244 'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
2246 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
2247 $self->{target_weight}{$copy_circ_lib} ||= 1;
2249 $prox_list{$prox} = [] unless defined($prox_list{$prox});
2250 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
2251 push @{$prox_list{$prox}}, $cp;
2257 sub volume_hold_capture {
2262 if (!defined($vols)) {
2264 $vols = [ asset::call_number->search( id => $hold->target ) ];
2265 $cache{cns}{$_->id} = $_ for (@$vols);
2266 } catch Error with {
2268 die "Could not retrieve initial volume list:\n\n$e\n";
2272 my @v_ids = map { $_->id } @$vols;
2276 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
2278 } catch Error with {
2280 warn "Could not retrieve copy list:\n\n$e\n";
2283 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
2286 sub title_hold_capture {
2291 if (!defined($titles)) {
2293 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
2294 $cache{titles}{$_->id} = $_ for (@$titles);
2295 } catch Error with {
2297 die "Could not retrieve initial title list:\n\n$e\n";
2301 my @t_ids = map { $_->id } @$titles;
2304 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
2306 } catch Error with {
2308 warn "Could not retrieve volume list:\n\n$e\n";
2311 $cache{cns}{$_->id} = $_ for (@$cn_list);
2313 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
2316 sub metarecord_hold_capture {
2322 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
2324 } catch Error with {
2326 die "Could not retrieve initial title list:\n\n$e\n";
2330 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
2332 $titles = [ biblio::record_entry->search( id => \@recs ) ];
2334 } catch Error with {
2336 die "Could not retrieve format-pruned title list:\n\n$e\n";
2340 $cache{titles}{$_->id} = $_ for (@$titles);
2341 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);