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;
20 return 1 if ($v == 1);
21 return 1 if ($v =~ /^t/io);
22 return 1 if ($v =~ /^y/io);
26 sub ou_ancestor_setting_value_or_cache {
27 # cache should be specific to setting
28 my ($actor, $org_id, $setting, $cache) = @_;
30 if (not exists $cache->{$org_id}) {
31 my $r = $actor->request(
32 'open-ils.actor.ou_setting.ancestor_default', $org_id, $setting
36 $cache->{$org_id} = $r->{value};
38 $cache->{$org_id} = undef;
41 return $cache->{$org_id};
44 my $parser = DateTime::Format::ISO8601->new;
45 my $log = 'OpenSRF::Utils::Logger';
47 sub open_noncat_circs {
52 my $a = action::non_cataloged_circulation->table;
53 my $c = config::non_cataloged_type->table;
58 JOIN $c c ON (a.item_type = c.id)
59 WHERE a.circ_time + c.circ_duration > current_timestamp
63 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
65 __PACKAGE__->register_method(
66 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
67 method => 'open_noncat_circs',
73 sub ou_hold_requests {
78 my $h_table = action::hold_request->table;
79 my $c_table = asset::copy->table;
80 my $o_table = actor::org_unit->table;
85 JOIN $c_table cp ON (cp.id = h.current_copy)
86 JOIN $o_table ou ON (ou.id = cp.circ_lib)
88 AND h.capture_time IS NULL
89 AND h.cancel_time IS NULL
90 AND (h.expire_time IS NULL OR h.expire_time > NOW())
91 ORDER BY h.request_time
94 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
97 $client->respond($_) for (
100 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
104 } @{ $sth->fetchall_arrayref }
108 __PACKAGE__->register_method(
109 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
113 method => 'ou_hold_requests',
118 my $upper_interval = shift || '1 millennium';
121 my $c_t = action::circulation->table;
126 WHERE stop_fines IS NULL
127 AND due_date < ( CURRENT_TIMESTAMP - grace_period )
128 AND fine_interval < ?::INTERVAL
131 my $sth = action::circulation->db_Main->prepare_cached($sql);
132 $sth->execute($upper_interval);
134 my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
136 $c_t = booking::reservation->table;
140 WHERE return_time IS NULL
141 AND end_time < ( CURRENT_TIMESTAMP )
142 AND fine_interval IS NOT NULL
143 AND cancel_time IS NULL
146 $sth = action::circulation->db_Main->prepare_cached($sql);
149 push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
154 sub complete_reshelving {
159 local $OpenILS::Application::Storage::WRITE = 1;
161 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
162 unless (interval_to_seconds( $window ));
164 my $setting = actor::org_unit_setting->table;
165 my $circ = action::circulation->table;
166 my $cp = asset::copy->table;
167 my $atc = action::transit_copy->table;
174 FROM (SELECT cp.id, MAX(circ.checkin_time), MAX(trans.dest_recv_time)
176 JOIN $circ circ ON (circ.target_copy = cp.id)
177 LEFT JOIN $atc trans ON (trans.target_copy = cp.id)
178 LEFT JOIN $setting setting
179 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
180 WHERE circ.checkin_time IS NOT NULL
184 ( ( MAX(circ.checkin_time) > MAX(trans.dest_recv_time) or MAX(trans.dest_recv_time) IS NULL )
185 AND MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
187 ( MAX(trans.dest_recv_time) > MAX(circ.checkin_time)
188 AND MAX(trans.dest_recv_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
194 LEFT JOIN $setting setting
195 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
196 LEFT JOIN $circ circ ON (circ.target_copy = cp.id)
199 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
202 my $sth = action::circulation->db_Main->prepare_cached($sql);
203 $sth->execute($window, $window, $window);
208 __PACKAGE__->register_method(
209 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
212 method => 'complete_reshelving',
215 sub mark_longoverdue {
220 local $OpenILS::Application::Storage::WRITE = 1;
222 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
223 unless (interval_to_seconds( $window ));
225 my $setting = actor::org_unit_setting->table;
226 my $circ = action::circulation->table;
230 SET stop_fines = 'LONGOVERDUE',
231 stop_fines_time = now()
235 LEFT JOIN $setting setting
236 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
237 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
238 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
242 my $sth = action::circulation->db_Main->prepare_cached($sql);
243 $sth->execute($window);
248 __PACKAGE__->register_method(
249 api_name => 'open-ils.storage.action.circulation.long_overdue',
252 method => 'mark_longoverdue',
255 sub auto_thaw_frozen_holds {
259 local $OpenILS::Application::Storage::WRITE = 1;
261 my $holds = action::hold_request->table;
263 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
265 my $sth = action::hold_request->db_Main->prepare_cached($sql);
271 __PACKAGE__->register_method(
272 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
276 method => 'auto_thaw_frozen_holds',
283 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
285 $client->respond( $idlist ? $_ : $_->to_fieldmapper ) for ( overdue_circs('', $idlist) );
290 __PACKAGE__->register_method(
291 api_name => 'open-ils.storage.action.circulation.overdue',
294 method => 'grab_overdue',
296 Return list of overdue circulations and reservations to be used for fine generation.
297 Despite the name, this is not a generic method for retrieving all overdue loans,
298 as it excludes loans that have already hit the maximum fine limit.
301 __PACKAGE__->register_method(
302 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
305 method => 'grab_overdue',
313 my $limit = int(shift()) || 10;
314 my $age = shift() || '0 seconds';
317 local $OpenILS::Application::Storage::WRITE = 1;
319 my $holdsort = isTrue($fifo) ?
320 "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 " :
321 "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 ";
323 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
325 FROM action.hold_request h
326 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
327 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
328 JOIN actor.usr au ON (au.id = h.usr)
329 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
330 WHERE hm.target_copy = ?
331 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
332 AND h.capture_time IS NULL
333 AND h.cancel_time IS NULL
334 AND (h.expire_time IS NULL OR h.expire_time > NOW())
335 AND h.frozen IS FALSE
340 $client->respond( $_ ) for ( @$ids );
343 __PACKAGE__->register_method(
344 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
347 method => 'nearest_hold',
350 sub targetable_holds {
353 my $check_expire = shift;
355 $check_expire ||= '12h';
357 local $OpenILS::Application::Storage::WRITE = 1;
359 # json_query can *almost* represent this query, but can't
360 # handle the CASE statement or the interval arithmetic
361 my $query = <<" SQL";
362 SELECT ahr.id, mmsm.metarecord
363 FROM action.hold_request ahr
364 JOIN reporter.hold_request_record USING (id)
365 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
366 WHERE capture_time IS NULL
367 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
368 AND fulfillment_time IS NULL
369 AND cancel_time IS NULL
371 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
373 my $sth = action::hold_request->db_Main->prepare_cached($query);
374 $sth->execute($check_expire);
376 $client->respond( $_ ) for ( $sth->fetchall_arrayref );
380 __PACKAGE__->register_method(
381 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
384 method => 'targetable_holds',
386 Returns ordered list of hold request and metarecord IDs
387 for all hold requests that are available for initial targeting
389 @param check interval
390 @return list of pairs of hold request and metarecord IDs
394 sub next_resp_group_id {
398 # XXX This is not replication safe!!!
400 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
401 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
405 __PACKAGE__->register_method(
406 api_name => 'open-ils.storage.action.survey_response.next_group_id',
408 method => 'next_resp_group_id',
411 sub patron_circ_summary {
416 return undef unless ($id);
417 my $c_table = action::circulation->table;
418 my $b_table = money::billing->table;
420 $log->debug("Retrieving patron summary for id $id", DEBUG);
422 my $select = <<" SQL";
423 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
425 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
427 AND c.xact_finish IS NULL
429 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
430 OR c.stop_fines IS NULL
434 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
436 __PACKAGE__->register_method(
437 api_name => 'open-ils.storage.action.circulation.patron_summary',
439 method => 'patron_circ_summary',
442 #XXX Fix stored proc calls
443 sub find_local_surveys {
448 return undef unless ($ou);
449 my $s_table = action::survey->table;
451 my $select = <<" SQL";
454 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
455 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
458 my $sth = action::survey->db_Main->prepare_cached($select);
461 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
465 __PACKAGE__->register_method(
466 api_name => 'open-ils.storage.action.survey.all',
469 method => 'find_local_surveys',
472 #XXX Fix stored proc calls
473 sub find_opac_surveys {
478 return undef unless ($ou);
479 my $s_table = action::survey->table;
481 my $select = <<" SQL";
484 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
485 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
489 my $sth = action::survey->db_Main->prepare_cached($select);
492 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
496 __PACKAGE__->register_method(
497 api_name => 'open-ils.storage.action.survey.opac',
500 method => 'find_opac_surveys',
507 my $limit = shift || 10;
508 my $offset = shift || 0;
510 return undef unless ($ou);
511 my $h_table = action::hold_request->table;
512 my $a_table = asset::copy->table;
513 my $ord_table = asset::copy_location_order->table;
515 my $idlist = 1 if ($self->api_name =~/id_list/o);
516 my $count = 1 if ($self->api_name =~/count$/o);
518 my $status_filter = '';
519 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
521 my $select = <<" SQL";
524 JOIN $a_table a ON (h.current_copy = a.id)
525 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
527 AND h.capture_time IS NULL
528 AND h.cancel_time IS NULL
529 AND (h.expire_time IS NULL OR h.expire_time > NOW())
531 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
540 JOIN $a_table a ON (h.current_copy = a.id)
542 AND h.capture_time IS NULL
543 AND h.cancel_time IS NULL
544 AND (h.expire_time IS NULL OR h.expire_time > NOW())
549 my $sth = action::survey->db_Main->prepare_cached($select);
553 $client->respond( $sth->fetchall_arrayref()->[0][0] );
555 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
557 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
562 __PACKAGE__->register_method(
563 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
567 "Returns a count of holds for a specific library's pull list.",
568 [ [org_unit => "The library's org id", "number"] ],
569 ['A count of holds for the stated library to pull ', 'number']
571 method => 'hold_pull_list',
573 __PACKAGE__->register_method(
574 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
578 "Returns a status filtered count of holds for a specific library's pull list.",
579 [ [org_unit => "The library's org id", "number"] ],
580 ['A status filtered count of holds for the stated library to pull ', 'number']
582 method => 'hold_pull_list',
584 __PACKAGE__->register_method(
585 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
589 "Returns the hold ids for a specific library's pull list.",
590 [ [org_unit => "The library's org id", "number"],
591 [limit => 'An optional page size, defaults to 10', 'number'],
592 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
594 ['A list of holds for the stated library to pull for', 'array']
596 method => 'hold_pull_list',
598 __PACKAGE__->register_method(
599 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
603 "Returns the holds for a specific library's pull list.",
604 [ [org_unit => "The library's org id", "number"],
605 [limit => 'An optional page size, defaults to 10', 'number'],
606 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
608 ['A list of holds for the stated library to pull for', 'array']
610 method => 'hold_pull_list',
612 __PACKAGE__->register_method(
613 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
617 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
618 [ [org_unit => "The library's org id", "number"],
619 [limit => 'An optional page size, defaults to 10', 'number'],
620 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
622 ['A list of holds for the stated library to pull for', 'array']
624 method => 'hold_pull_list',
626 __PACKAGE__->register_method(
627 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
631 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
632 [ [org_unit => "The library's org id", "number"],
633 [limit => 'An optional page size, defaults to 10', 'number'],
634 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
636 ['A list of holds for the stated library to pull for', 'array']
638 method => 'hold_pull_list',
641 sub find_optional_surveys {
646 return undef unless ($ou);
647 my $s_table = action::survey->table;
649 my $select = <<" SQL";
652 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
653 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
654 AND s.required IS FALSE;
657 my $sth = action::survey->db_Main->prepare_cached($select);
660 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
664 __PACKAGE__->register_method(
665 api_name => 'open-ils.storage.action.survey.optional',
668 method => 'find_optional_surveys',
671 sub find_required_surveys {
676 return undef unless ($ou);
677 my $s_table = action::survey->table;
679 my $select = <<" SQL";
682 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
683 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
684 AND s.required IS TRUE;
687 my $sth = action::survey->db_Main->prepare_cached($select);
690 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
694 __PACKAGE__->register_method(
695 api_name => 'open-ils.storage.action.survey.required',
698 method => 'find_required_surveys',
701 sub find_usr_summary_surveys {
706 return undef unless ($ou);
707 my $s_table = action::survey->table;
709 my $select = <<" SQL";
712 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
713 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
714 AND s.usr_summary IS TRUE;
717 my $sth = action::survey->db_Main->prepare_cached($select);
720 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
724 __PACKAGE__->register_method(
725 api_name => 'open-ils.storage.action.survey.usr_summary',
728 method => 'find_usr_summary_surveys',
731 sub seconds_to_interval_hash {
732 my $interval = shift;
733 my $limit = shift || 's';
734 $limit =~ s/^(.)/$1/o;
738 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
739 my ($year, $month, $week, $day, $hour, $minute, $second) =
740 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
742 if ($y = int($interval / (60 * 60 * 24 * 365))) {
744 $ym = $interval % (60 * 60 * 24 * 365);
748 return %output if ($limit eq 'y');
750 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
751 $output{$month} = $M;
752 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
756 return %output if ($limit eq 'M');
758 if ($w = int($Mm / 604800)) {
764 return %output if ($limit eq 'w');
766 if ($d = int($wm / 86400)) {
772 return %output if ($limit eq 'd');
774 if ($h = int($dm / 3600)) {
780 return %output if ($limit eq 'h');
782 if ($m = int($hm / 60)) {
783 $output{$minute} = $m;
788 return %output if ($limit eq 'm');
791 $output{$second} = $s;
793 $output{$second} = 0 unless (keys %output);
803 my $overbill = shift;
805 local $OpenILS::Application::Storage::WRITE = 1;
810 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
811 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
813 push @circs, overdue_circs();
816 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
818 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
822 $ctype =~ s/^.+::(\w+)$/$1/;
824 my $due_date_method = 'due_date';
825 my $target_copy_method = 'target_copy';
826 my $circ_lib_method = 'circ_lib';
827 my $recurring_fine_method = 'recurring_fine';
828 my $is_reservation = 0;
829 if ($ctype eq 'reservation') {
831 $due_date_method = 'end_time';
832 $target_copy_method = 'current_resource';
833 $circ_lib_method = 'pickup_lib';
834 $recurring_fine_method = 'fine_amount';
835 next unless ($c->fine_interval);
837 #TODO: reservation grace periods
838 my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
841 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
842 $log->debug("Cleaning up after previous transaction\n");
843 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
845 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
847 sprintf("Processing %s %d...",
848 ($is_reservation ? "reservation" : "circ"), $c->id
853 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
855 my $due = $due_dt->epoch;
858 my $fine_interval = $c->fine_interval;
859 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
860 $fine_interval = interval_to_seconds( $fine_interval );
862 if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
863 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
864 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
868 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
870 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
871 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
874 $due -= ($due % $fine_interval) + $tz_offset_s;
875 $now -= ($now % $fine_interval) + $tz_offset_s;
879 "ARG! Overdue $ctype ".$c->id.
880 " for item ".$c->$target_copy_method.
881 " (user ".$c->usr.").\n".
882 "\tItem was due on or before: ".localtime($due)."\n");
884 my @fines = money::billing->search_where(
887 billing_ts => { '>' => $c->$due_date_method } },
888 { order_by => 'billing_ts DESC'}
892 my $fine = $fines[$f_idx] if (@fines);
894 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
897 my $current_fine_total = 0;
898 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
902 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
903 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
905 $log->info( "Potential first billing for circ ".$c->id );
908 $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});
911 next if ($last_fine > $now);
912 # Generate fines for each past interval, including the one we are inside
913 my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
915 if ( $last_fine == $due # we have no fines yet
916 && $grace_period # and we have a grace period
917 && $now < $due + $grace_period # and some date math says were are within the grace period
919 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
920 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
924 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
925 next unless ($pending_fine_count);
927 my $recurring_fine = int($c->$recurring_fine_method * 100);
928 my $max_fine = int($c->max_fine * 100);
930 my ($latest_billing_ts, $latest_amount) = ('',0);
931 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
933 if ($current_fine_total >= $max_fine) {
934 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
936 "\tMaximum fine level of ".$c->max_fine.
937 " reached for this $ctype.\n".
938 "\tNo more fines will be generated.\n" );
942 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
943 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
944 my $current_bill_count = $bill;
945 while ( $current_bill_count ) {
946 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
947 $current_bill_count--;
950 my $dow = $billing_ts->day_of_week_0();
951 my $dow_open = "dow_${dow}_open";
952 my $dow_close = "dow_${dow}_close";
954 if (my $h = $hoo{$c->$circ_lib_method}) {
955 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
958 my $timestamptz = $billing_ts->strftime('%FT%T%z');
959 my @cl = actor::org_unit::closed_date->search_where(
960 { close_start => { '<=' => $timestamptz },
961 close_end => { '>=' => $timestamptz },
962 org_unit => $c->$circ_lib_method }
966 $current_fine_total += $recurring_fine;
967 $latest_amount += $recurring_fine;
968 $latest_billing_ts = $timestamptz;
970 money::billing->create(
972 note => "System Generated Overdue Fine",
973 billing_type => "Overdue materials",
975 amount => sprintf('%0.2f', $recurring_fine/100),
976 billing_ts => $timestamptz,
982 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
983 if ($latest_billing_ts and $latest_amount);
985 $self->method_lookup('open-ils.storage.transaction.commit')->run;
989 # Caluclate penalties inline
990 OpenILS::Utils::Penalty->calculate_penalties(
991 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
995 # Calculate penalties with an aysnc call to the penalty server. This approach
996 # may lead to duplicate penalties since multiple penalty processes for a
997 # given user may be running at the same time. Leave this here for reference
998 # in case we later find that asyc calls are needed in some environments.
1000 'open-ils.penalty.patron_penalty.calculate',
1001 { patronid => ''.$c->usr,
1002 context_org => ''.$c->$circ_lib_method,
1009 } catch Error with {
1011 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
1012 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
1013 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1014 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1018 __PACKAGE__->register_method(
1019 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1022 method => 'generate_fines',
1027 sub new_hold_copy_targeter {
1030 my $check_expire = shift;
1031 my $one_hold = shift;
1032 my $find_copy = shift;
1034 local $OpenILS::Application::Storage::WRITE = 1;
1036 $self->{target_weight} = {};
1037 $self->{max_loops} = {};
1043 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1044 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
1045 } elsif ( $check_expire ) {
1047 # what's the retarget time threashold?
1049 $check_expire ||= '12h';
1050 $check_expire = interval_to_seconds( $check_expire );
1052 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1055 my $expire_threshold = sprintf(
1056 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1057 $year, $mon, $mday, $hour, $min, $sec
1060 # find all the holds holds needing retargeting
1061 $holds = [ action::hold_request->search_where(
1062 { capture_time => undef,
1063 fulfillment_time => undef,
1064 cancel_time => undef,
1066 prev_check_time => { '<=' => $expire_threshold },
1068 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
1070 # find all the holds holds needing first time targeting
1071 push @$holds, action::hold_request->search(
1072 capture_time => undef,
1073 fulfillment_time => undef,
1074 prev_check_time => undef,
1076 cancel_time => undef,
1077 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
1080 # find all the holds holds needing first time targeting ONLY
1081 $holds = [ action::hold_request->search(
1082 capture_time => undef,
1083 fulfillment_time => undef,
1084 prev_check_time => undef,
1085 cancel_time => undef,
1087 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
1089 } catch Error with {
1091 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1094 my @closed = actor::org_unit::closed_date->search_where(
1095 { close_start => { '<=', 'now' },
1096 close_end => { '>=', 'now' } }
1099 if ($check_expire) {
1101 # $check_expire, if it exists, was already converted to seconds
1102 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1106 my $next_check_time = sprintf(
1107 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1108 $year, $mon, $mday, $hour, $min, $sec
1112 my @closed_at_next = actor::org_unit::closed_date->search_where(
1113 { close_start => { '<=', $next_check_time },
1114 close_end => { '>=', $next_check_time } }
1118 for my $c_at_n (@closed_at_next) {
1119 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1120 push @new_closed, $c_at_n;
1123 @closed = @new_closed;
1127 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1129 my $target_when_closed = {};
1130 my $target_when_closed_if_at_pickup_lib = {};
1132 for my $hold (@$holds) {
1134 #start a transaction if needed
1135 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1136 $log->debug("Cleaning up after previous transaction\n");
1137 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1139 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1140 $log->info("Processing hold ".$hold->id."...\n");
1142 #first, re-fetch the hold, to make sure it's not captured already
1143 $hold->remove_from_object_index();
1144 $hold = action::hold_request->retrieve( $hold->id );
1146 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1148 # remove old auto-targeting maps
1149 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1150 $_->delete for (@oldmaps);
1152 if ($hold->expire_time) {
1153 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1154 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1156 # cancel cause = un-targeted expiration
1157 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1158 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1160 # tell A/T the hold was cancelled
1161 my $fm_hold = $hold->to_fieldmapper;
1162 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1163 $ses->request('open-ils.trigger.event.autocreate',
1164 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1170 my $all_copies = [];
1172 # find filters for MR holds
1173 my ($types, $formats, $lang);
1174 if (defined($hold->holdable_formats)) {
1175 ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1178 # find all the potential copies
1179 if ($hold->hold_type eq 'M') {
1182 metabib::record_descriptor
1186 isTrue($_->deleted) ? () : ($_->id)
1187 } metabib::metarecord->retrieve($hold->target)->source_records
1189 ( $types ? (item_type => [split '', $types]) : () ),
1190 ( $formats ? (item_form => [split '', $formats]) : () ),
1191 ( $lang ? (item_lang => $lang) : () ),
1195 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1196 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1198 for my $cn ( @{ $rtree->call_numbers } ) {
1200 asset::copy->search_where(
1201 { id => [map {$_->id} @{ $cn->copies }],
1203 ) if ($cn && @{ $cn->copies });
1206 } elsif ($hold->hold_type eq 'T') {
1208 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1209 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1212 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1216 for my $cn ( @{ $rtree->call_numbers } ) {
1218 asset::copy->search_where(
1219 { id => [map {$_->id} @{ $cn->copies }],
1221 ) if ($cn && @{ $cn->copies });
1223 } elsif ($hold->hold_type eq 'V') {
1225 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1226 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1229 asset::copy->search_where(
1230 { id => [map {$_->id} @{ $vtree->copies }],
1232 ) if ($vtree && @{ $vtree->copies });
1234 } elsif ($hold->hold_type eq 'P') {
1235 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1237 asset::copy->search_where(
1238 { id => [map {$_->target_copy} @part_maps],
1243 } elsif ($hold->hold_type eq 'I') {
1245 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1246 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1249 asset::copy->search_where(
1250 { id => [map {$_->unit->id} @{ $itree->items }],
1252 ) if ($itree && @{ $itree->items });
1254 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1255 my $_cp = asset::copy->retrieve($hold->target);
1256 push @$all_copies, $_cp if $_cp;
1260 @$all_copies = grep { isTrue($_->status->holdable) &&
1261 isTrue($_->location->holdable) &&
1262 isTrue($_->holdable) &&
1263 !isTrue($_->deleted) &&
1264 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1265 ($hold->hold_type ne 'P' ? $_->part_maps->count == 0 : 1)
1268 # let 'em know we're still working
1269 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1271 # if we have no copies ...
1272 if (!ref $all_copies || !@$all_copies) {
1273 $log->info("\tNo copies available for targeting at all!\n");
1274 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1276 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1277 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1281 my $copy_count = @$all_copies;
1282 my $found_copy = undef;
1283 $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1285 # map the potentials, so that we can pick up checkins
1286 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1287 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1288 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1289 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1291 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1294 for my $c (@$all_copies) {
1296 next if ($c->id eq $hold->current_copy);
1298 # skip on circ lib is closed IFF we care
1301 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1302 $ignore_closing = ou_ancestor_setting_value_or_cache(
1305 'circ.holds.target_when_closed_if_at_pickup_lib',
1306 $target_when_closed_if_at_pickup_lib
1309 if (not $ignore_closing) { # one more chance to find a reason
1310 # to ignore OU closedness.
1311 $ignore_closing = ou_ancestor_setting_value_or_cache(
1314 'circ.holds.target_when_closed',
1320 # "For hold " . $hold->id . " and copy with circ_lib " .
1321 # $c->circ_lib . " we " .
1322 # ($ignore_closing ? "ignore" : "respect")
1327 (not $ignore_closing) and
1328 (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1331 # target of another hold
1332 next if (action::hold_request
1334 { current_copy => $c->id,
1335 fulfillment_time => undef,
1336 cancel_time => undef,
1341 # we passed all three, keep it
1342 push @good_copies, $c if ($c);
1343 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1346 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1348 my $old_best = $hold->current_copy;
1349 $hold->update({ current_copy => undef }) if ($old_best);
1351 if (!scalar(@good_copies)) {
1352 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1353 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1354 # the old copy is still available
1355 $log->debug("\tPushing current_copy back onto the targeting list");
1356 push @good_copies, $old_best;
1358 # oops, old copy is not available
1359 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1360 $hold->update( { prev_check_time => 'today' } );
1361 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1362 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1367 my $pu_lib = ''.$hold->pickup_lib;
1373 ''.$_->circ_lib eq $pu_lib &&
1374 ( $_->status == 0 || $_->status == 7 )
1378 $all_copies = [grep { $_->status == 0 || $_->status == 7 } grep {''.$_->circ_lib ne $pu_lib } @good_copies];
1379 # $all_copies is now a list of copies not at the pickup library
1381 my $best = choose_nearest_copy($hold, $prox_list);
1382 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1385 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1387 $self->{max_loops}{$pu_lib} = $actor->request(
1388 'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1391 if (defined($self->{max_loops}{$pu_lib})) {
1392 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1394 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1395 my $circ_lib_list = [keys %circ_lib_map];
1397 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1399 # Grab the "biggest" loop for this hold so far
1400 my $current_loop = $cstore->request(
1401 'open-ils.cstore.json_query',
1403 select => { aufhmxl => ['max'] },
1405 where => { hold => $hold->id}
1409 $current_loop = $current_loop->{max} if ($current_loop);
1410 $current_loop ||= 1;
1412 my $exclude_list = $cstore->request(
1413 'open-ils.cstore.json_query.atomic',
1415 select => { aufhol => ['circ_lib'] },
1417 where => { hold => $hold->id}
1422 if ($exclude_list && @$exclude_list) {
1423 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1424 # check to see if we've used up every library in the potentials list
1425 for my $l ( @$circ_lib_list ) {
1427 for my $ex ( @$exclude_list ) {
1433 push(@keepers, $l) if ($keep);
1436 @keepers = @$circ_lib_list;
1439 $current_loop++ if (!@keepers);
1441 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1442 # We haven't exceeded max_loops yet
1444 for my $cp ( @$all_copies ) {
1445 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1448 $all_copies = [@keeper_copies];
1450 # We have, and should remove potentials and cancel the hold
1451 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1452 $_->delete for (@oldmaps);
1454 # cancel cause = un-targeted expiration
1455 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1456 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1458 # tell A/T the hold was cancelled
1459 my $fm_hold = $hold->to_fieldmapper;
1460 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1461 $ses->request('open-ils.trigger.event.autocreate',
1462 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1468 $prox_list = create_prox_list( $self, $pu_lib, $all_copies );
1470 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1472 $best = choose_nearest_copy($hold, $prox_list);
1475 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1477 # hold wasn't fulfilled, record the fact
1479 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1480 action::unfulfilled_hold_list->create(
1481 { hold => ''.$hold->id,
1482 current_copy => ''.$old_best->id,
1483 circ_lib => ''.$old_best->circ_lib,
1488 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1489 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1492 !action::hold_request
1494 { current_copy => $old_best->id,
1495 fulfillment_time => undef,
1496 cancel_time => undef,
1500 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1501 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1503 $hold->update( { prev_check_time => 'now' } );
1504 $log->info( "\tThere were no targetable copies for the hold" );
1505 process_recall($actor, $log, $hold, \@good_copies);
1508 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1509 $log->info("\tProcessing of hold ".$hold->id." complete.");
1512 { hold => $hold->id,
1513 old_target => ($old_best ? $old_best->id : undef),
1514 eligible_copies => $copy_count,
1515 target => ($best ? $best->id : undef),
1516 found_copy => $found_copy };
1521 $log->error("Processing of hold failed: $e");
1522 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1523 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1530 __PACKAGE__->register_method(
1531 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1533 method => 'new_hold_copy_targeter',
1536 sub process_recall {
1537 my ($actor, $log, $hold, $good_copies) = @_;
1539 # Bail early if we don't have required settings to avoid spurious requests
1540 my ($recall_threshold, $return_interval, $fine_rules);
1542 my $rv = $actor->request(
1543 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1547 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1550 $recall_threshold = $rv->{value};
1552 $rv = $actor->request(
1553 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1557 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1560 $return_interval = $rv->{value};
1562 $rv = $actor->request(
1563 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1567 $fine_rules = $rv->{value};
1570 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1572 # We want checked out copies (status = 1) at the hold pickup lib
1573 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1575 my @copy_ids = map { $_->id } @$all_copies;
1577 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1579 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1581 # Iterate over the checked-out copies to find a copy with a
1582 # loan period longer than the recall threshold:
1583 my $circs = [ action::circulation->search_where(
1584 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1585 { order_by => 'due_date ASC' }
1588 # If we have a candidate copy, then:
1589 if (scalar(@$circs)) {
1590 my $circ = $circs->[0];
1591 $log->info("Recalling circ ID : " . $circ->id);
1593 # Give the user a new due date of either a full recall threshold,
1594 # or the return interval, whichever is further in the future
1595 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1596 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1597 $return_date = $threshold_date;
1600 my $update_fields = {
1601 due_date => $return_date,
1602 renewal_remaining => 0,
1605 # If the OU hasn't defined new fine rules for recalls, keep them
1608 $log->info("Apply recall fine rules: $fine_rules");
1609 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1610 $update_fields->{recurring_fine} = $rules->[0];
1611 $update_fields->{fine_interval} = $rules->[1];
1612 $update_fields->{max_fine} = $rules->[2];
1615 # Adjust circ for current user
1616 $circ->update($update_fields);
1618 # Create trigger event for notifying current user
1619 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1620 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1623 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1626 sub reservation_targeter {
1629 my $one_reservation = shift;
1631 local $OpenILS::Application::Storage::WRITE = 1;
1636 if ($one_reservation) {
1637 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1638 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1641 # find all the reservations needing targeting
1643 booking::reservation->search_where(
1644 { current_resource => undef,
1645 cancel_time => undef,
1646 start_time => { '>' => 'now' }
1648 { order_by => 'start_time' }
1652 } catch Error with {
1654 die "Could not retrieve reservation requests:\n\n$e\n";
1658 for my $bresv (@$reservations) {
1660 #start a transaction if needed
1661 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1662 $log->debug("Cleaning up after previous transaction\n");
1663 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1665 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1666 $log->info("Processing reservation ".$bresv->id."...\n");
1668 #first, re-fetch the hold, to make sure it's not captured already
1669 $bresv->remove_from_object_index();
1670 $bresv = booking::reservation->retrieve( $bresv->id );
1672 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1674 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1675 if (DateTime->compare($end_time, DateTime->now) < 0) {
1677 # cancel cause = un-targeted expiration
1678 $bresv->update( { cancel_time => 'now' } );
1679 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1681 # tell A/T the reservation was cancelled
1682 my $fm_bresv = $bresv->to_fieldmapper;
1683 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1684 $ses->request('open-ils.trigger.event.autocreate',
1685 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1690 my $possible_resources;
1692 # find all the potential resources
1693 if (!$bresv->target_resource) {
1694 my $filter = { type => $bresv->target_resource_type };
1695 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1697 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1699 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1700 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1701 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1703 $possible_resources = $bresv->target_resource;
1706 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1707 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1710 my @good_resources = ();
1712 for my $res (@$all_resources) {
1713 unless (isTrue($res->type->catalog_item)) {
1714 push @good_resources, $res;
1718 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1721 push @good_resources, $res;
1725 # At this point, if we're just targeting one specific
1726 # resource, just succeed. We don't care about its present
1728 if ($bresv->target_resource) {
1729 push @good_resources, $res;
1733 if ($copy->status->id == 0 || $copy->status->id == 7) {
1734 push @good_resources, $res;
1738 if ($copy->status->id == 1) {
1739 my $circs = [ action::circulation->search_where(
1740 {target_copy => $copy->id, checkin_time => undef },
1741 { order_by => 'id DESC' }
1745 my $due_date = $circs->[0]->due_date;
1746 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1747 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1748 if (DateTime->compare($start_time, $due_date) < 0) {
1749 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1753 push @good_resources, $res;
1759 push @good_resources, $res if (isTrue($copy->status->holdable));
1762 # let 'em know we're still working
1763 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1765 # if we have no copies ...
1766 if (!@good_resources) {
1767 $log->info("\tNo resources available for targeting at all!\n");
1768 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1771 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1775 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1781 $_->owner == $bresv->pickup_lib
1785 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1786 # $all_copies is now a list of copies not at the pickup library
1788 my $best = shift @good_resources;
1789 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1792 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1796 sort { $a->[0] <=> $b->[0] }
1798 [ actor::org_unit_proximity->search_where(
1799 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1805 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1807 $best = shift @$prox_list
1811 $bresv->update( { current_resource => ''.$best->id } );
1812 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1815 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1816 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1819 { reservation => $bresv->id,
1820 current_resource => ($best ? $best->id : undef) };
1825 $log->error("Processing of bresv failed: $e");
1826 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1827 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1834 __PACKAGE__->register_method(
1835 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1837 method => 'reservation_targeter',
1842 my %cache = (titles => {}, cns => {});
1844 sub copy_hold_capture {
1849 if (!defined($cps)) {
1851 $cps = [ asset::copy->search( id => $hold->target ) ];
1852 } catch Error with {
1854 die "Could not retrieve initial volume list:\n\n$e\n";
1858 my @copies = grep { $_->holdable } @$cps;
1860 for (my $i = 0; $i < @$cps; $i++) {
1861 next unless $$cps[$i];
1863 my $cn = $cache{cns}{$copies[$i]->call_number};
1864 my $rec = $cache{titles}{$cn->record};
1865 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1866 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1867 $copies[$i] = undef if (
1869 !$self->{user_filter}->request(
1870 'open-ils.circ.permit_hold',
1871 $hold->to_fieldmapper, do {
1872 my $cp_fm = $copies[$i]->to_fieldmapper;
1873 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1874 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1875 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1878 { title => $rec->to_fieldmapper,
1879 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1880 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1883 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1886 @copies = grep { $_ } @copies;
1888 my $count = @copies;
1890 return unless ($count);
1892 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1895 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1896 for my $c (@copies) {
1897 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1899 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1905 sub choose_nearest_copy {
1907 my $prox_list = shift;
1909 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1910 next unless (ref $$prox_list[$p]);
1912 my @capturable = @{ $$prox_list[$p] };
1913 next unless (@capturable);
1915 my $rand = int(rand(scalar(@capturable)));
1917 while (my ($c) = splice(@capturable, $rand, 1)) {
1918 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
1919 { title => $c->call_number->record->to_fieldmapper,
1920 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1921 patron => $hold->usr->to_fieldmapper,
1922 copy => $c->to_fieldmapper,
1923 requestor => $hold->requestor->to_fieldmapper,
1924 request_lib => $hold->request_lib->to_fieldmapper,
1925 pickup_lib => $hold->pickup_lib->id,
1931 last unless(@capturable);
1932 $rand = int(rand(scalar(@capturable)));
1937 sub create_prox_list {
1942 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1945 for my $cp (@$copies) {
1946 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1947 next unless (defined($prox));
1949 my $copy_circ_lib = ''.$cp->circ_lib;
1950 # Fetch the weighting value for hold targeting, defaulting to 1
1951 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
1952 'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
1954 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
1955 $self->{target_weight}{$copy_circ_lib} ||= 1;
1957 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1958 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
1959 push @{$prox_list[$prox]}, $cp;
1965 sub volume_hold_capture {
1970 if (!defined($vols)) {
1972 $vols = [ asset::call_number->search( id => $hold->target ) ];
1973 $cache{cns}{$_->id} = $_ for (@$vols);
1974 } catch Error with {
1976 die "Could not retrieve initial volume list:\n\n$e\n";
1980 my @v_ids = map { $_->id } @$vols;
1984 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1986 } catch Error with {
1988 warn "Could not retrieve copy list:\n\n$e\n";
1991 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1994 sub title_hold_capture {
1999 if (!defined($titles)) {
2001 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
2002 $cache{titles}{$_->id} = $_ for (@$titles);
2003 } catch Error with {
2005 die "Could not retrieve initial title list:\n\n$e\n";
2009 my @t_ids = map { $_->id } @$titles;
2012 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
2014 } catch Error with {
2016 warn "Could not retrieve volume list:\n\n$e\n";
2019 $cache{cns}{$_->id} = $_ for (@$cn_list);
2021 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
2024 sub metarecord_hold_capture {
2030 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
2032 } catch Error with {
2034 die "Could not retrieve initial title list:\n\n$e\n";
2038 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
2040 $titles = [ biblio::record_entry->search( id => \@recs ) ];
2042 } catch Error with {
2044 die "Could not retrieve format-pruned title list:\n\n$e\n";
2048 $cache{titles}{$_->id} = $_ for (@$titles);
2049 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);