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";
23 return 1 if ($v == 1);
24 return 1 if ($v =~ /^t/io);
25 return 1 if ($v =~ /^y/io);
29 sub ou_ancestor_setting_value_or_cache {
30 # cache should be specific to setting
31 my ($actor, $org_id, $setting, $cache) = @_;
33 if (not exists $cache->{$org_id}) {
34 my $r = $actor->request(
35 'open-ils.actor.ou_setting.ancestor_default', $org_id, $setting
39 $cache->{$org_id} = $r->{value};
41 $cache->{$org_id} = undef;
44 return $cache->{$org_id};
47 my $parser = DateTime::Format::ISO8601->new;
48 my $log = 'OpenSRF::Utils::Logger';
50 sub open_noncat_circs {
55 my $a = action::non_cataloged_circulation->table;
56 my $c = config::non_cataloged_type->table;
61 JOIN $c c ON (a.item_type = c.id)
62 WHERE a.circ_time + c.circ_duration > current_timestamp
66 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
68 __PACKAGE__->register_method(
69 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
70 method => 'open_noncat_circs',
76 sub ou_hold_requests {
81 my $h_table = action::hold_request->table;
82 my $c_table = asset::copy->table;
83 my $o_table = actor::org_unit->table;
88 JOIN $c_table cp ON (cp.id = h.current_copy)
89 JOIN $o_table ou ON (ou.id = cp.circ_lib)
91 AND h.capture_time IS NULL
92 AND h.cancel_time IS NULL
93 AND (h.expire_time IS NULL OR h.expire_time > NOW())
94 ORDER BY h.request_time
97 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
100 $client->respond($_) for (
103 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
107 } @{ $sth->fetchall_arrayref }
111 __PACKAGE__->register_method(
112 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
116 method => 'ou_hold_requests',
121 my $upper_interval = shift || '1 millennium';
124 my $c_t = action::circulation->table;
129 WHERE stop_fines IS NULL
130 AND due_date < ( CURRENT_TIMESTAMP - grace_period )
131 AND fine_interval < ?::INTERVAL
134 my $sth = action::circulation->db_Main->prepare_cached($sql);
135 $sth->execute($upper_interval);
137 my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
139 $c_t = booking::reservation->table;
143 WHERE return_time IS NULL
144 AND end_time < ( CURRENT_TIMESTAMP )
145 AND fine_interval IS NOT NULL
146 AND cancel_time IS NULL
149 $sth = action::circulation->db_Main->prepare_cached($sql);
152 push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
157 sub complete_reshelving {
162 local $OpenILS::Application::Storage::WRITE = 1;
164 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
165 unless (interval_to_seconds( $window ));
167 my $cp = asset::copy->table;
176 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)
179 my $sth = action::circulation->db_Main->prepare_cached($sql);
180 $sth->execute($window);
185 __PACKAGE__->register_method(
186 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
189 method => 'complete_reshelving',
192 sub mark_longoverdue {
197 local $OpenILS::Application::Storage::WRITE = 1;
199 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
200 unless (interval_to_seconds( $window ));
202 my $setting = actor::org_unit_setting->table;
203 my $circ = action::circulation->table;
207 SET stop_fines = 'LONGOVERDUE',
208 stop_fines_time = now()
212 LEFT JOIN $setting setting
213 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
214 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
215 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
219 my $sth = action::circulation->db_Main->prepare_cached($sql);
220 $sth->execute($window);
225 __PACKAGE__->register_method(
226 api_name => 'open-ils.storage.action.circulation.long_overdue',
229 method => 'mark_longoverdue',
232 sub auto_thaw_frozen_holds {
236 local $OpenILS::Application::Storage::WRITE = 1;
238 my $holds = action::hold_request->table;
240 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
242 my $sth = action::hold_request->db_Main->prepare_cached($sql);
248 __PACKAGE__->register_method(
249 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
253 method => 'auto_thaw_frozen_holds',
260 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
262 $client->respond( $idlist ? $_ : $_->to_fieldmapper ) for ( overdue_circs('', $idlist) );
267 __PACKAGE__->register_method(
268 api_name => 'open-ils.storage.action.circulation.overdue',
271 method => 'grab_overdue',
273 Return list of overdue circulations and reservations to be used for fine generation.
274 Despite the name, this is not a generic method for retrieving all overdue loans,
275 as it excludes loans that have already hit the maximum fine limit.
278 __PACKAGE__->register_method(
279 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
282 method => 'grab_overdue',
290 my $limit = int(shift()) || 10;
291 my $age = shift() || '0 seconds';
294 local $OpenILS::Application::Storage::WRITE = 1;
296 my $holdsort = isTrue($fifo) ?
297 "pgt.hold_priority, CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END, h.request_time, h.selection_depth DESC, p.prox " :
298 "p.prox, pgt.hold_priority, CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END, h.selection_depth DESC, h.request_time ";
300 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
302 FROM action.hold_request h
303 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
304 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
305 JOIN actor.usr au ON (au.id = h.usr)
306 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
307 LEFT JOIN actor.usr_standing_penalty ausp
308 ON ( au.id = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
309 LEFT JOIN config.standing_penalty csp
310 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
311 WHERE hm.target_copy = ?
312 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
313 AND h.capture_time IS NULL
314 AND h.cancel_time IS NULL
315 AND (h.expire_time IS NULL OR h.expire_time > NOW())
316 AND h.frozen IS FALSE
318 ORDER BY CASE WHEN h.hold_type IN ('R','F') THEN 0 ELSE 1 END, $holdsort
322 $client->respond( $_ ) for ( @$ids );
325 __PACKAGE__->register_method(
326 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
329 method => 'nearest_hold',
332 sub targetable_holds {
335 my $check_expire = shift;
337 $check_expire ||= '12h';
339 local $OpenILS::Application::Storage::WRITE = 1;
341 # json_query can *almost* represent this query, but can't
342 # handle the CASE statement or the interval arithmetic
343 my $query = <<" SQL";
344 SELECT ahr.id, mmsm.metarecord
345 FROM action.hold_request ahr
346 JOIN reporter.hold_request_record USING (id)
347 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
348 WHERE capture_time IS NULL
349 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
350 AND fulfillment_time IS NULL
351 AND cancel_time IS NULL
353 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
355 my $sth = action::hold_request->db_Main->prepare_cached($query);
356 $sth->execute($check_expire);
357 $client->respond( $_ ) for @{ $sth->fetchall_arrayref };
362 __PACKAGE__->register_method(
363 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
366 method => 'targetable_holds',
368 Returns ordered list of hold request and metarecord IDs
369 for all hold requests that are available for initial targeting
371 @param check interval
372 @return list of pairs of hold request and metarecord IDs
376 sub next_resp_group_id {
380 # XXX This is not replication safe!!!
382 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
383 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
387 __PACKAGE__->register_method(
388 api_name => 'open-ils.storage.action.survey_response.next_group_id',
390 method => 'next_resp_group_id',
393 sub patron_circ_summary {
398 return undef unless ($id);
399 my $c_table = action::circulation->table;
400 my $b_table = money::billing->table;
402 $log->debug("Retrieving patron summary for id $id", DEBUG);
404 my $select = <<" SQL";
405 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
407 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
409 AND c.xact_finish IS NULL
411 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
412 OR c.stop_fines IS NULL
416 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
418 __PACKAGE__->register_method(
419 api_name => 'open-ils.storage.action.circulation.patron_summary',
421 method => 'patron_circ_summary',
424 #XXX Fix stored proc calls
425 sub find_local_surveys {
430 return undef unless ($ou);
431 my $s_table = action::survey->table;
433 my $select = <<" SQL";
436 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
437 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
440 my $sth = action::survey->db_Main->prepare_cached($select);
443 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
447 __PACKAGE__->register_method(
448 api_name => 'open-ils.storage.action.survey.all',
451 method => 'find_local_surveys',
454 #XXX Fix stored proc calls
455 sub find_opac_surveys {
460 return undef unless ($ou);
461 my $s_table = action::survey->table;
463 my $select = <<" SQL";
466 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
467 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
471 my $sth = action::survey->db_Main->prepare_cached($select);
474 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
478 __PACKAGE__->register_method(
479 api_name => 'open-ils.storage.action.survey.opac',
482 method => 'find_opac_surveys',
489 my $limit = shift || 10;
490 my $offset = shift || 0;
492 return undef unless ($ou);
493 my $h_table = action::hold_request->table;
494 my $a_table = asset::copy->table;
495 my $ord_table = asset::copy_location_order->table;
497 my $idlist = 1 if ($self->api_name =~/id_list/o);
498 my $count = 1 if ($self->api_name =~/count$/o);
500 my $status_filter = '';
501 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
503 my $select = <<" SQL";
506 JOIN $a_table a ON (h.current_copy = a.id)
507 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
508 LEFT JOIN actor.usr_standing_penalty ausp
509 ON ( h.usr = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
510 LEFT JOIN config.standing_penalty csp
511 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
513 AND h.capture_time IS NULL
514 AND h.cancel_time IS NULL
515 AND (h.expire_time IS NULL OR h.expire_time > NOW())
518 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
527 JOIN $a_table a ON (h.current_copy = a.id)
528 LEFT JOIN actor.usr_standing_penalty ausp
529 ON ( h.usr = ausp.usr AND ( ausp.stop_date IS NULL OR ausp.stop_date > NOW() ) )
530 LEFT JOIN config.standing_penalty csp
531 ON ( csp.id = ausp.standing_penalty AND csp.block_list LIKE '%CAPTURE%' )
533 AND h.capture_time IS NULL
534 AND h.cancel_time IS NULL
535 AND (h.expire_time IS NULL OR h.expire_time > NOW())
541 my $sth = action::survey->db_Main->prepare_cached($select);
545 $client->respond( $sth->fetchall_arrayref()->[0][0] );
547 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
549 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
554 __PACKAGE__->register_method(
555 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
559 "Returns a count of holds for a specific library's pull list.",
560 [ [org_unit => "The library's org id", "number"] ],
561 ['A count of holds for the stated library to pull ', 'number']
563 method => 'hold_pull_list',
565 __PACKAGE__->register_method(
566 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
570 "Returns a status filtered count of holds for a specific library's pull list.",
571 [ [org_unit => "The library's org id", "number"] ],
572 ['A status filtered count of holds for the stated library to pull ', 'number']
574 method => 'hold_pull_list',
576 __PACKAGE__->register_method(
577 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
581 "Returns the hold ids for a specific library's pull list.",
582 [ [org_unit => "The library's org id", "number"],
583 [limit => 'An optional page size, defaults to 10', 'number'],
584 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
586 ['A list of holds for the stated library to pull for', 'array']
588 method => 'hold_pull_list',
590 __PACKAGE__->register_method(
591 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
595 "Returns the holds for a specific library's pull list.",
596 [ [org_unit => "The library's org id", "number"],
597 [limit => 'An optional page size, defaults to 10', 'number'],
598 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
600 ['A list of holds for the stated library to pull for', 'array']
602 method => 'hold_pull_list',
604 __PACKAGE__->register_method(
605 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
609 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
610 [ [org_unit => "The library's org id", "number"],
611 [limit => 'An optional page size, defaults to 10', 'number'],
612 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
614 ['A list of holds for the stated library to pull for', 'array']
616 method => 'hold_pull_list',
618 __PACKAGE__->register_method(
619 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
623 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
624 [ [org_unit => "The library's org id", "number"],
625 [limit => 'An optional page size, defaults to 10', 'number'],
626 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
628 ['A list of holds for the stated library to pull for', 'array']
630 method => 'hold_pull_list',
633 sub find_optional_surveys {
638 return undef unless ($ou);
639 my $s_table = action::survey->table;
641 my $select = <<" SQL";
644 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
645 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
646 AND s.required IS FALSE;
649 my $sth = action::survey->db_Main->prepare_cached($select);
652 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
656 __PACKAGE__->register_method(
657 api_name => 'open-ils.storage.action.survey.optional',
660 method => 'find_optional_surveys',
663 sub find_required_surveys {
668 return undef unless ($ou);
669 my $s_table = action::survey->table;
671 my $select = <<" SQL";
674 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
675 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
676 AND s.required IS TRUE;
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.required',
690 method => 'find_required_surveys',
693 sub find_usr_summary_surveys {
698 return undef unless ($ou);
699 my $s_table = action::survey->table;
701 my $select = <<" SQL";
704 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
705 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
706 AND s.usr_summary IS TRUE;
709 my $sth = action::survey->db_Main->prepare_cached($select);
712 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
716 __PACKAGE__->register_method(
717 api_name => 'open-ils.storage.action.survey.usr_summary',
720 method => 'find_usr_summary_surveys',
723 sub seconds_to_interval_hash {
724 my $interval = shift;
725 my $limit = shift || 's';
726 $limit =~ s/^(.)/$1/o;
730 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
731 my ($year, $month, $week, $day, $hour, $minute, $second) =
732 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
734 if ($y = int($interval / (60 * 60 * 24 * 365))) {
736 $ym = $interval % (60 * 60 * 24 * 365);
740 return %output if ($limit eq 'y');
742 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
743 $output{$month} = $M;
744 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
748 return %output if ($limit eq 'M');
750 if ($w = int($Mm / 604800)) {
756 return %output if ($limit eq 'w');
758 if ($d = int($wm / 86400)) {
764 return %output if ($limit eq 'd');
766 if ($h = int($dm / 3600)) {
772 return %output if ($limit eq 'h');
774 if ($m = int($hm / 60)) {
775 $output{$minute} = $m;
780 return %output if ($limit eq 'm');
783 $output{$second} = $s;
785 $output{$second} = 0 unless (keys %output);
795 my $overbill = shift;
797 local $OpenILS::Application::Storage::WRITE = 1;
802 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
803 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
805 push @circs, overdue_circs();
808 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
810 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
814 $ctype =~ s/^.+::(\w+)$/$1/;
816 my $due_date_method = 'due_date';
817 my $target_copy_method = 'target_copy';
818 my $circ_lib_method = 'circ_lib';
819 my $recurring_fine_method = 'recurring_fine';
820 my $is_reservation = 0;
821 if ($ctype eq 'reservation') {
823 $due_date_method = 'end_time';
824 $target_copy_method = 'current_resource';
825 $circ_lib_method = 'pickup_lib';
826 $recurring_fine_method = 'fine_amount';
827 next unless ($c->fine_interval);
829 #TODO: reservation grace periods
830 my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
833 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
834 $log->debug("Cleaning up after previous transaction\n");
835 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
837 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
839 sprintf("Processing %s %d...",
840 ($is_reservation ? "reservation" : "circ"), $c->id
845 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
847 my $due = $due_dt->epoch;
850 my $fine_interval = $c->fine_interval;
851 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
852 $fine_interval = interval_to_seconds( $fine_interval );
854 if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
855 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
856 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
860 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
862 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
863 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
866 $due -= ($due % $fine_interval) + $tz_offset_s;
867 $now -= ($now % $fine_interval) + $tz_offset_s;
871 "ARG! Overdue $ctype ".$c->id.
872 " for item ".$c->$target_copy_method.
873 " (user ".$c->usr.").\n".
874 "\tItem was due on or before: ".localtime($due)."\n");
876 my @fines = money::billing->search_where(
879 billing_ts => { '>' => $c->$due_date_method } },
880 { order_by => 'billing_ts DESC'}
884 my $fine = $fines[$f_idx] if (@fines);
886 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
889 my $current_fine_total = 0;
890 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
894 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
895 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
897 $log->info( "Potential first billing for circ ".$c->id );
900 $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});
903 next if ($last_fine > $now);
904 # Generate fines for each past interval, including the one we are inside
905 my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
907 if ( $last_fine == $due # we have no fines yet
908 && $grace_period # and we have a grace period
909 && $now < $due + $grace_period # and some date math says were are within the grace period
911 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
912 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
916 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
917 next unless ($pending_fine_count);
919 my $recurring_fine = int($c->$recurring_fine_method * 100);
920 my $max_fine = int($c->max_fine * 100);
922 my $skip_closed_check = $U->ou_ancestor_setting_value(
923 $c->$circ_lib_method->to_fieldmapper->id, 'circ.fines.charge_when_closed');
924 $skip_closed_check = $U->is_true($skip_closed_check);
926 my ($latest_billing_ts, $latest_amount) = ('',0);
927 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
929 if ($current_fine_total >= $max_fine) {
930 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
932 "\tMaximum fine level of ".$c->max_fine.
933 " reached for this $ctype.\n".
934 "\tNo more fines will be generated.\n" );
938 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
939 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
940 my $current_bill_count = $bill;
941 while ( $current_bill_count ) {
942 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
943 $current_bill_count--;
946 my $timestamptz = $billing_ts->strftime('%FT%T%z');
947 if (!$skip_closed_check) {
948 my $dow = $billing_ts->day_of_week_0();
949 my $dow_open = "dow_${dow}_open";
950 my $dow_close = "dow_${dow}_close";
952 if (my $h = $hoo{$c->$circ_lib_method}) {
953 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
956 my @cl = actor::org_unit::closed_date->search_where(
957 { close_start => { '<=' => $timestamptz },
958 close_end => { '>=' => $timestamptz },
959 org_unit => $c->$circ_lib_method }
964 $current_fine_total += $recurring_fine;
965 $latest_amount += $recurring_fine;
966 $latest_billing_ts = $timestamptz;
968 money::billing->create(
970 note => "System Generated Overdue Fine",
971 billing_type => "Overdue materials",
973 amount => sprintf('%0.2f', $recurring_fine/100),
974 billing_ts => $timestamptz,
980 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
981 if ($latest_billing_ts and $latest_amount);
983 $self->method_lookup('open-ils.storage.transaction.commit')->run;
987 # Caluclate penalties inline
988 OpenILS::Utils::Penalty->calculate_penalties(
989 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
993 # Calculate penalties with an aysnc call to the penalty server. This approach
994 # may lead to duplicate penalties since multiple penalty processes for a
995 # given user may be running at the same time. Leave this here for reference
996 # in case we later find that asyc calls are needed in some environments.
998 'open-ils.penalty.patron_penalty.calculate',
999 { patronid => ''.$c->usr,
1000 context_org => ''.$c->$circ_lib_method,
1007 } catch Error with {
1009 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
1010 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
1011 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1012 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1016 __PACKAGE__->register_method(
1017 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1020 method => 'generate_fines',
1025 sub new_hold_copy_targeter {
1028 my $check_expire = shift;
1029 my $one_hold = shift;
1030 my $find_copy = shift;
1032 local $OpenILS::Application::Storage::WRITE = 1;
1034 $self->{target_weight} = {};
1035 $self->{max_loops} = {};
1041 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1042 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
1043 } elsif ( $check_expire ) {
1045 # what's the retarget time threashold?
1047 $check_expire ||= '12h';
1048 $check_expire = interval_to_seconds( $check_expire );
1050 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1053 my $expire_threshold = sprintf(
1054 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1055 $year, $mon, $mday, $hour, $min, $sec
1058 # find all the holds holds needing retargeting
1059 $holds = [ action::hold_request->search_where(
1060 { capture_time => undef,
1061 fulfillment_time => undef,
1062 cancel_time => undef,
1064 prev_check_time => { '<=' => $expire_threshold },
1066 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
1068 # find all the holds holds needing first time targeting
1069 push @$holds, action::hold_request->search(
1070 capture_time => undef,
1071 fulfillment_time => undef,
1072 prev_check_time => undef,
1074 cancel_time => undef,
1075 { order_by => 'selection_depth DESC, request_time' } );
1078 # find all the holds holds needing first time targeting ONLY
1079 $holds = [ action::hold_request->search(
1080 capture_time => undef,
1081 fulfillment_time => undef,
1082 prev_check_time => undef,
1083 cancel_time => undef,
1085 { order_by => 'selection_depth DESC, request_time' } ) ];
1087 } catch Error with {
1089 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1092 my @closed = actor::org_unit::closed_date->search_where(
1093 { close_start => { '<=', 'now' },
1094 close_end => { '>=', 'now' } }
1097 if ($check_expire) {
1099 # $check_expire, if it exists, was already converted to seconds
1100 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1104 my $next_check_time = sprintf(
1105 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1106 $year, $mon, $mday, $hour, $min, $sec
1110 my @closed_at_next = actor::org_unit::closed_date->search_where(
1111 { close_start => { '<=', $next_check_time },
1112 close_end => { '>=', $next_check_time } }
1116 for my $c_at_n (@closed_at_next) {
1117 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1118 push @new_closed, $c_at_n;
1121 @closed = @new_closed;
1125 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1127 my $target_when_closed = {};
1128 my $target_when_closed_if_at_pickup_lib = {};
1130 for my $hold (@$holds) {
1132 #start a transaction if needed
1133 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1134 $log->debug("Cleaning up after previous transaction\n");
1135 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1137 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1138 $log->info("Processing hold ".$hold->id."...\n");
1140 #first, re-fetch the hold, to make sure it's not captured already
1141 $hold->remove_from_object_index();
1142 $hold = action::hold_request->retrieve( $hold->id );
1144 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1146 # remove old auto-targeting maps
1147 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1148 $_->delete for (@oldmaps);
1150 if ($hold->expire_time) {
1151 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1152 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1154 # cancel cause = un-targeted expiration
1155 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1157 # refresh fields from the DB while still in the xact
1158 my $fm_hold = $hold->to_fieldmapper;
1160 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1162 # tell A/T the hold was cancelled
1163 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1164 $ses->request('open-ils.trigger.event.autocreate',
1165 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1171 my $all_copies = [];
1173 # find filters for MR holds
1174 my ($types, $formats, $lang);
1175 if (defined($hold->holdable_formats)) {
1176 ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1179 # find all the potential copies
1180 if ($hold->hold_type eq 'M') {
1183 isTrue($_->deleted) ? () : ($_->id)
1184 } metabib::metarecord->retrieve($hold->target)->source_records
1189 metabib::record_descriptor
1192 ( $types ? (item_type => [split '', $types]) : () ),
1193 ( $formats ? (item_form => [split '', $formats]) : () ),
1194 ( $lang ? (item_lang => $lang) : () ),
1198 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1199 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1201 for my $cn ( @{ $rtree->call_numbers } ) {
1203 asset::copy->search_where(
1204 { id => [map {$_->id} @{ $cn->copies }],
1206 ) if ($cn && @{ $cn->copies });
1210 } elsif ($hold->hold_type eq 'T') {
1212 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1213 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1216 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1220 for my $cn ( @{ $rtree->call_numbers } ) {
1222 asset::copy->search_where(
1223 { id => [map {$_->id} @{ $cn->copies }],
1225 ) if ($cn && @{ $cn->copies });
1227 } elsif ($hold->hold_type eq 'V') {
1229 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1230 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1233 asset::copy->search_where(
1234 { id => [map {$_->id} @{ $vtree->copies }],
1236 ) if ($vtree && @{ $vtree->copies });
1238 } elsif ($hold->hold_type eq 'P') {
1239 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1241 asset::copy->search_where(
1242 { id => [map {$_->target_copy} @part_maps],
1247 } elsif ($hold->hold_type eq 'I') {
1249 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1250 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1253 asset::copy->search_where(
1254 { id => [map {$_->unit->id} @{ $itree->items }],
1256 ) if ($itree && @{ $itree->items });
1258 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1259 my $_cp = asset::copy->retrieve($hold->target);
1260 push @$all_copies, $_cp if $_cp;
1263 # Force and recall holds bypass pretty much everything
1264 if ($hold->hold_type ne 'R' && $hold->hold_type ne 'F') {
1266 @$all_copies = grep { isTrue($_->status->holdable) &&
1267 isTrue($_->location->holdable) &&
1268 isTrue($_->holdable) &&
1269 !isTrue($_->deleted) &&
1270 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1271 ($hold->hold_type ne 'P' ? $_->part_maps->count == 0 : 1)
1275 # let 'em know we're still working
1276 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1278 # if we have no copies ...
1279 if (!ref $all_copies || !@$all_copies) {
1280 $log->info("\tNo copies available for targeting at all!\n");
1281 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1283 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1284 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1288 my $copy_count = @$all_copies;
1289 my $found_copy = undef;
1290 $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1292 # map the potentials, so that we can pick up checkins
1293 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1294 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1295 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1296 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1298 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1301 for my $c (@$all_copies) {
1303 next if ($hold->current_copy and $c->id eq $hold->current_copy);
1305 # skip on circ lib is closed IFF we care
1308 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1309 $ignore_closing = ou_ancestor_setting_value_or_cache(
1312 'circ.holds.target_when_closed_if_at_pickup_lib',
1313 $target_when_closed_if_at_pickup_lib
1316 if (not $ignore_closing) { # one more chance to find a reason
1317 # to ignore OU closedness.
1318 $ignore_closing = ou_ancestor_setting_value_or_cache(
1321 'circ.holds.target_when_closed',
1327 # "For hold " . $hold->id . " and copy with circ_lib " .
1328 # $c->circ_lib . " we " .
1329 # ($ignore_closing ? "ignore" : "respect")
1334 (not $ignore_closing) and
1335 (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1338 # target of another hold
1339 next if (action::hold_request
1341 { current_copy => $c->id,
1342 fulfillment_time => undef,
1343 cancel_time => undef,
1348 # we passed all three, keep it
1349 push @good_copies, $c if ($c);
1350 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1353 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1355 my $old_best = $hold->current_copy;
1356 my $old_best_still_valid = 0; # Assume no, but the next line says yes if it is still a potential.
1357 $old_best_still_valid = 1 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies );
1358 $hold->update({ current_copy => undef }) if ($old_best);
1360 if (!scalar(@good_copies)) {
1361 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1362 if ( $old_best_still_valid ) {
1363 # the old copy is still available
1364 $log->debug("\tPushing current_copy back onto the targeting list");
1365 push @good_copies, $old_best;
1367 # oops, old copy is not available
1368 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1369 $hold->update( { prev_check_time => 'today' } );
1370 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1371 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1376 my $pu_lib = ''.$hold->pickup_lib;
1382 ''.$_->circ_lib eq $pu_lib &&
1383 ( $_->status == 0 || $_->status == 7 )
1387 $all_copies = [grep { $_->status == 0 || $_->status == 7 } grep {''.$_->circ_lib ne $pu_lib } @good_copies];
1388 # $all_copies is now a list of copies not at the pickup library
1391 if ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') { # Recall/Force holds bypass hold rules.
1392 $best = $good_copies[0] if(scalar @good_copies);
1394 $best = choose_nearest_copy($hold, $prox_list);
1396 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1399 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1401 $self->{max_loops}{$pu_lib} = $actor->request(
1402 'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1405 if (defined($self->{max_loops}{$pu_lib})) {
1406 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1408 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1409 my $circ_lib_list = [keys %circ_lib_map];
1411 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1413 # Grab the "biggest" loop for this hold so far
1414 my $current_loop = $cstore->request(
1415 'open-ils.cstore.json_query',
1417 select => { aufhmxl => ['max'] },
1419 where => { hold => $hold->id}
1423 $current_loop = $current_loop->{max} if ($current_loop);
1424 $current_loop ||= 1;
1426 my $exclude_list = $cstore->request(
1427 'open-ils.cstore.json_query.atomic',
1429 select => { aufhol => ['circ_lib'] },
1431 where => { hold => $hold->id}
1436 if ($exclude_list && @$exclude_list) {
1437 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1438 # check to see if we've used up every library in the potentials list
1439 for my $l ( @$circ_lib_list ) {
1441 for my $ex ( @$exclude_list ) {
1447 push(@keepers, $l) if ($keep);
1450 @keepers = @$circ_lib_list;
1453 $current_loop++ if (!@keepers);
1455 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1456 # We haven't exceeded max_loops yet
1458 for my $cp ( @$all_copies ) {
1459 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1462 $all_copies = [@keeper_copies];
1464 # We have, and should remove potentials and cancel the hold
1465 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1466 $_->delete for (@oldmaps);
1468 # cancel cause = un-targeted expiration
1469 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1471 # refresh fields from the DB while still in the xact
1472 my $fm_hold = $hold->to_fieldmapper;
1474 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1476 # tell A/T the hold was cancelled
1477 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1478 $ses->request('open-ils.trigger.event.autocreate',
1479 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1485 $prox_list = create_prox_list( $self, $pu_lib, $all_copies );
1487 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1489 $best = choose_nearest_copy($hold, $prox_list);
1492 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1494 # hold wasn't fulfilled, record the fact
1496 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1497 action::unfulfilled_hold_list->create(
1498 { hold => ''.$hold->id,
1499 current_copy => ''.$old_best->id,
1500 circ_lib => ''.$old_best->circ_lib,
1505 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1506 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1508 $old_best_still_valid &&
1509 !action::hold_request
1511 { current_copy => $old_best->id,
1512 fulfillment_time => undef,
1513 cancel_time => undef,
1516 ( OpenILS::Utils::PermitHold::permit_copy_hold(
1517 { title => $old_best->call_number->record->to_fieldmapper,
1518 title_descriptor => $old_best->call_number->record->record_descriptor->next->to_fieldmapper,
1519 patron => $hold->usr->to_fieldmapper,
1520 copy => $old_best->to_fieldmapper,
1521 requestor => $hold->requestor->to_fieldmapper,
1522 request_lib => $hold->request_lib->to_fieldmapper,
1523 pickup_lib => $hold->pickup_lib->id,
1528 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1529 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1531 $hold->update( { prev_check_time => 'now' } );
1532 $log->info( "\tThere were no targetable copies for the hold" );
1533 process_recall($actor, $log, $hold, \@good_copies);
1536 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1537 $log->info("\tProcessing of hold ".$hold->id." complete.");
1540 { hold => $hold->id,
1541 old_target => ($old_best ? $old_best->id : undef),
1542 eligible_copies => $copy_count,
1543 target => ($best ? $best->id : undef),
1544 found_copy => $found_copy };
1549 $log->error("Processing of hold failed: $e");
1550 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1551 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1558 __PACKAGE__->register_method(
1559 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1561 method => 'new_hold_copy_targeter',
1564 sub process_recall {
1565 my ($actor, $log, $hold, $good_copies) = @_;
1567 # Bail early if we don't have required settings to avoid spurious requests
1568 my ($recall_threshold, $return_interval, $fine_rules);
1570 my $rv = $actor->request(
1571 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1575 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1578 $recall_threshold = $rv->{value};
1580 $rv = $actor->request(
1581 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1585 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1588 $return_interval = $rv->{value};
1590 $rv = $actor->request(
1591 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1595 $fine_rules = $rv->{value};
1598 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1600 # We want checked out copies (status = 1) at the hold pickup lib
1601 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1603 my @copy_ids = map { $_->id } @$all_copies;
1605 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1607 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1609 # Iterate over the checked-out copies to find a copy with a
1610 # loan period longer than the recall threshold:
1611 my $circs = [ action::circulation->search_where(
1612 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1613 { order_by => 'due_date ASC' }
1616 # If we have a candidate copy, then:
1617 if (scalar(@$circs)) {
1618 my $circ = $circs->[0];
1619 $log->info("Recalling circ ID : " . $circ->id);
1621 # Give the user a new due date of either a full recall threshold,
1622 # or the return interval, whichever is further in the future
1623 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1624 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1625 $return_date = $threshold_date;
1628 my $update_fields = {
1629 due_date => $return_date,
1630 renewal_remaining => 0,
1633 # If the OU hasn't defined new fine rules for recalls, keep them
1636 $log->info("Apply recall fine rules: $fine_rules");
1637 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1638 $update_fields->{recurring_fine} = $rules->[0];
1639 $update_fields->{fine_interval} = $rules->[1];
1640 $update_fields->{max_fine} = $rules->[2];
1643 # Adjust circ for current user
1644 $circ->update($update_fields);
1646 # Create trigger event for notifying current user
1647 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1648 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1651 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1654 sub reservation_targeter {
1657 my $one_reservation = shift;
1659 local $OpenILS::Application::Storage::WRITE = 1;
1664 if ($one_reservation) {
1665 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1666 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1669 # find all the reservations needing targeting
1671 booking::reservation->search_where(
1672 { current_resource => undef,
1673 cancel_time => undef,
1674 start_time => { '>' => 'now' }
1676 { order_by => 'start_time' }
1680 } catch Error with {
1682 die "Could not retrieve reservation requests:\n\n$e\n";
1686 for my $bresv (@$reservations) {
1688 #start a transaction if needed
1689 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1690 $log->debug("Cleaning up after previous transaction\n");
1691 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1693 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1694 $log->info("Processing reservation ".$bresv->id."...\n");
1696 #first, re-fetch the hold, to make sure it's not captured already
1697 $bresv->remove_from_object_index();
1698 $bresv = booking::reservation->retrieve( $bresv->id );
1700 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1702 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1703 if (DateTime->compare($end_time, DateTime->now) < 0) {
1705 # cancel cause = un-targeted expiration
1706 $bresv->update( { cancel_time => 'now' } );
1708 # refresh fields from the DB while still in the xact
1709 my $fm_bresv = $bresv->to_fieldmapper;
1711 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1713 # tell A/T the reservation was cancelled
1714 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1715 $ses->request('open-ils.trigger.event.autocreate',
1716 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1721 my $possible_resources;
1723 # find all the potential resources
1724 if (!$bresv->target_resource) {
1725 my $filter = { type => $bresv->target_resource_type };
1726 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1728 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1730 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1731 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1732 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1734 $possible_resources = $bresv->target_resource;
1737 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1738 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1741 my @good_resources = ();
1743 for my $res (@$all_resources) {
1744 unless (isTrue($res->type->catalog_item)) {
1745 push @good_resources, $res;
1749 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1752 push @good_resources, $res;
1756 # At this point, if we're just targeting one specific
1757 # resource, just succeed. We don't care about its present
1759 if ($bresv->target_resource) {
1760 push @good_resources, $res;
1764 if ($copy->status->id == 0 || $copy->status->id == 7) {
1765 push @good_resources, $res;
1769 if ($copy->status->id == 1) {
1770 my $circs = [ action::circulation->search_where(
1771 {target_copy => $copy->id, checkin_time => undef },
1772 { order_by => 'id DESC' }
1776 my $due_date = $circs->[0]->due_date;
1777 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1778 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1779 if (DateTime->compare($start_time, $due_date) < 0) {
1780 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1784 push @good_resources, $res;
1790 push @good_resources, $res if (isTrue($copy->status->holdable));
1793 # let 'em know we're still working
1794 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1796 # if we have no copies ...
1797 if (!@good_resources) {
1798 $log->info("\tNo resources available for targeting at all!\n");
1799 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1802 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1806 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1812 $_->owner == $bresv->pickup_lib
1816 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1817 # $all_copies is now a list of copies not at the pickup library
1819 my $best = shift @good_resources;
1820 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1823 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1827 sort { $a->[0] <=> $b->[0] }
1829 [ actor::org_unit_proximity->search_where(
1830 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1836 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1838 $best = shift @$prox_list
1842 $bresv->update( { current_resource => ''.$best->id } );
1843 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1846 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1847 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1850 { reservation => $bresv->id,
1851 current_resource => ($best ? $best->id : undef) };
1856 $log->error("Processing of bresv failed: $e");
1857 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1858 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1865 __PACKAGE__->register_method(
1866 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1868 method => 'reservation_targeter',
1873 my %cache = (titles => {}, cns => {});
1875 sub copy_hold_capture {
1880 if (!defined($cps)) {
1882 $cps = [ asset::copy->search( id => $hold->target ) ];
1883 } catch Error with {
1885 die "Could not retrieve initial volume list:\n\n$e\n";
1889 my @copies = grep { $_->holdable } @$cps;
1891 for (my $i = 0; $i < @$cps; $i++) {
1892 next unless $$cps[$i];
1894 my $cn = $cache{cns}{$copies[$i]->call_number};
1895 my $rec = $cache{titles}{$cn->record};
1896 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1897 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1898 $copies[$i] = undef if (
1900 !$self->{user_filter}->request(
1901 'open-ils.circ.permit_hold',
1902 $hold->to_fieldmapper, do {
1903 my $cp_fm = $copies[$i]->to_fieldmapper;
1904 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1905 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1906 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1909 { title => $rec->to_fieldmapper,
1910 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1911 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1914 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1917 @copies = grep { $_ } @copies;
1919 my $count = @copies;
1921 return unless ($count);
1923 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1926 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1927 for my $c (@copies) {
1928 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1930 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1936 sub choose_nearest_copy {
1938 my $prox_list = shift;
1940 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1941 next unless (ref $$prox_list[$p]);
1943 my @capturable = @{ $$prox_list[$p] };
1944 next unless (@capturable);
1946 my $rand = int(rand(scalar(@capturable)));
1948 while (my ($c) = splice(@capturable, $rand, 1)) {
1949 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
1950 { title => $c->call_number->record->to_fieldmapper,
1951 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1952 patron => $hold->usr->to_fieldmapper,
1953 copy => $c->to_fieldmapper,
1954 requestor => $hold->requestor->to_fieldmapper,
1955 request_lib => $hold->request_lib->to_fieldmapper,
1956 pickup_lib => $hold->pickup_lib->id,
1962 last unless(@capturable);
1963 $rand = int(rand(scalar(@capturable)));
1968 sub create_prox_list {
1973 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1976 for my $cp (@$copies) {
1977 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1978 next unless (defined($prox));
1980 my $copy_circ_lib = ''.$cp->circ_lib;
1981 # Fetch the weighting value for hold targeting, defaulting to 1
1982 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
1983 'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
1985 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
1986 $self->{target_weight}{$copy_circ_lib} ||= 1;
1988 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1989 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
1990 push @{$prox_list[$prox]}, $cp;
1996 sub volume_hold_capture {
2001 if (!defined($vols)) {
2003 $vols = [ asset::call_number->search( id => $hold->target ) ];
2004 $cache{cns}{$_->id} = $_ for (@$vols);
2005 } catch Error with {
2007 die "Could not retrieve initial volume list:\n\n$e\n";
2011 my @v_ids = map { $_->id } @$vols;
2015 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
2017 } catch Error with {
2019 warn "Could not retrieve copy list:\n\n$e\n";
2022 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
2025 sub title_hold_capture {
2030 if (!defined($titles)) {
2032 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
2033 $cache{titles}{$_->id} = $_ for (@$titles);
2034 } catch Error with {
2036 die "Could not retrieve initial title list:\n\n$e\n";
2040 my @t_ids = map { $_->id } @$titles;
2043 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
2045 } catch Error with {
2047 warn "Could not retrieve volume list:\n\n$e\n";
2050 $cache{cns}{$_->id} = $_ for (@$cn_list);
2052 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
2055 sub metarecord_hold_capture {
2061 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
2063 } catch Error with {
2065 die "Could not retrieve initial title list:\n\n$e\n";
2069 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
2071 $titles = [ biblio::record_entry->search( id => \@recs ) ];
2073 } catch Error with {
2075 die "Could not retrieve format-pruned title list:\n\n$e\n";
2079 $cache{titles}{$_->id} = $_ for (@$titles);
2080 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);