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 $cp = asset::copy->table;
173 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)
176 my $sth = action::circulation->db_Main->prepare_cached($sql);
177 $sth->execute($window);
182 __PACKAGE__->register_method(
183 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
186 method => 'complete_reshelving',
189 sub mark_longoverdue {
194 local $OpenILS::Application::Storage::WRITE = 1;
196 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
197 unless (interval_to_seconds( $window ));
199 my $setting = actor::org_unit_setting->table;
200 my $circ = action::circulation->table;
204 SET stop_fines = 'LONGOVERDUE',
205 stop_fines_time = now()
209 LEFT JOIN $setting setting
210 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
211 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
212 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
216 my $sth = action::circulation->db_Main->prepare_cached($sql);
217 $sth->execute($window);
222 __PACKAGE__->register_method(
223 api_name => 'open-ils.storage.action.circulation.long_overdue',
226 method => 'mark_longoverdue',
229 sub auto_thaw_frozen_holds {
233 local $OpenILS::Application::Storage::WRITE = 1;
235 my $holds = action::hold_request->table;
237 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
239 my $sth = action::hold_request->db_Main->prepare_cached($sql);
245 __PACKAGE__->register_method(
246 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
250 method => 'auto_thaw_frozen_holds',
257 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
259 $client->respond( $idlist ? $_ : $_->to_fieldmapper ) for ( overdue_circs('', $idlist) );
264 __PACKAGE__->register_method(
265 api_name => 'open-ils.storage.action.circulation.overdue',
268 method => 'grab_overdue',
270 Return list of overdue circulations and reservations to be used for fine generation.
271 Despite the name, this is not a generic method for retrieving all overdue loans,
272 as it excludes loans that have already hit the maximum fine limit.
275 __PACKAGE__->register_method(
276 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
279 method => 'grab_overdue',
287 my $limit = int(shift()) || 10;
288 my $age = shift() || '0 seconds';
291 local $OpenILS::Application::Storage::WRITE = 1;
293 my $holdsort = isTrue($fifo) ?
294 "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 " :
295 "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 ";
297 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
299 FROM action.hold_request h
300 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
301 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
302 JOIN actor.usr au ON (au.id = h.usr)
303 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
304 WHERE hm.target_copy = ?
305 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
306 AND h.capture_time IS NULL
307 AND h.cancel_time IS NULL
308 AND (h.expire_time IS NULL OR h.expire_time > NOW())
309 AND h.frozen IS FALSE
310 ORDER BY CASE WHEN h.hold_type IN ('R','F') THEN 0 ELSE 1 END, $holdsort
314 $client->respond( $_ ) for ( @$ids );
317 __PACKAGE__->register_method(
318 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
321 method => 'nearest_hold',
324 sub targetable_holds {
327 my $check_expire = shift;
329 $check_expire ||= '12h';
331 local $OpenILS::Application::Storage::WRITE = 1;
333 # json_query can *almost* represent this query, but can't
334 # handle the CASE statement or the interval arithmetic
335 my $query = <<" SQL";
336 SELECT ahr.id, mmsm.metarecord
337 FROM action.hold_request ahr
338 JOIN reporter.hold_request_record USING (id)
339 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
340 WHERE capture_time IS NULL
341 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
342 AND fulfillment_time IS NULL
343 AND cancel_time IS NULL
345 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
347 my $sth = action::hold_request->db_Main->prepare_cached($query);
348 $sth->execute($check_expire);
349 $client->respond( $_ ) for @{ $sth->fetchall_arrayref };
354 __PACKAGE__->register_method(
355 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
358 method => 'targetable_holds',
360 Returns ordered list of hold request and metarecord IDs
361 for all hold requests that are available for initial targeting
363 @param check interval
364 @return list of pairs of hold request and metarecord IDs
368 sub next_resp_group_id {
372 # XXX This is not replication safe!!!
374 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
375 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
379 __PACKAGE__->register_method(
380 api_name => 'open-ils.storage.action.survey_response.next_group_id',
382 method => 'next_resp_group_id',
385 sub patron_circ_summary {
390 return undef unless ($id);
391 my $c_table = action::circulation->table;
392 my $b_table = money::billing->table;
394 $log->debug("Retrieving patron summary for id $id", DEBUG);
396 my $select = <<" SQL";
397 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
399 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
401 AND c.xact_finish IS NULL
403 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
404 OR c.stop_fines IS NULL
408 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
410 __PACKAGE__->register_method(
411 api_name => 'open-ils.storage.action.circulation.patron_summary',
413 method => 'patron_circ_summary',
416 #XXX Fix stored proc calls
417 sub find_local_surveys {
422 return undef unless ($ou);
423 my $s_table = action::survey->table;
425 my $select = <<" SQL";
428 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
429 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
432 my $sth = action::survey->db_Main->prepare_cached($select);
435 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
439 __PACKAGE__->register_method(
440 api_name => 'open-ils.storage.action.survey.all',
443 method => 'find_local_surveys',
446 #XXX Fix stored proc calls
447 sub find_opac_surveys {
452 return undef unless ($ou);
453 my $s_table = action::survey->table;
455 my $select = <<" SQL";
458 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
459 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
463 my $sth = action::survey->db_Main->prepare_cached($select);
466 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
470 __PACKAGE__->register_method(
471 api_name => 'open-ils.storage.action.survey.opac',
474 method => 'find_opac_surveys',
481 my $limit = shift || 10;
482 my $offset = shift || 0;
484 return undef unless ($ou);
485 my $h_table = action::hold_request->table;
486 my $a_table = asset::copy->table;
487 my $ord_table = asset::copy_location_order->table;
489 my $idlist = 1 if ($self->api_name =~/id_list/o);
490 my $count = 1 if ($self->api_name =~/count$/o);
492 my $status_filter = '';
493 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
495 my $select = <<" SQL";
498 JOIN $a_table a ON (h.current_copy = a.id)
499 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
501 AND h.capture_time IS NULL
502 AND h.cancel_time IS NULL
503 AND (h.expire_time IS NULL OR h.expire_time > NOW())
505 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
514 JOIN $a_table a ON (h.current_copy = a.id)
516 AND h.capture_time IS NULL
517 AND h.cancel_time IS NULL
518 AND (h.expire_time IS NULL OR h.expire_time > NOW())
523 my $sth = action::survey->db_Main->prepare_cached($select);
527 $client->respond( $sth->fetchall_arrayref()->[0][0] );
529 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
531 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
536 __PACKAGE__->register_method(
537 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
541 "Returns a count of holds for a specific library's pull list.",
542 [ [org_unit => "The library's org id", "number"] ],
543 ['A count of holds for the stated library to pull ', 'number']
545 method => 'hold_pull_list',
547 __PACKAGE__->register_method(
548 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
552 "Returns a status filtered count of holds for a specific library's pull list.",
553 [ [org_unit => "The library's org id", "number"] ],
554 ['A status filtered count of holds for the stated library to pull ', 'number']
556 method => 'hold_pull_list',
558 __PACKAGE__->register_method(
559 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
563 "Returns the hold ids for a specific library's pull list.",
564 [ [org_unit => "The library's org id", "number"],
565 [limit => 'An optional page size, defaults to 10', 'number'],
566 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
568 ['A list of holds for the stated library to pull for', 'array']
570 method => 'hold_pull_list',
572 __PACKAGE__->register_method(
573 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
577 "Returns the holds for a specific library's pull list.",
578 [ [org_unit => "The library's org id", "number"],
579 [limit => 'An optional page size, defaults to 10', 'number'],
580 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
582 ['A list of holds for the stated library to pull for', 'array']
584 method => 'hold_pull_list',
586 __PACKAGE__->register_method(
587 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
591 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
592 [ [org_unit => "The library's org id", "number"],
593 [limit => 'An optional page size, defaults to 10', 'number'],
594 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
596 ['A list of holds for the stated library to pull for', 'array']
598 method => 'hold_pull_list',
600 __PACKAGE__->register_method(
601 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
605 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
606 [ [org_unit => "The library's org id", "number"],
607 [limit => 'An optional page size, defaults to 10', 'number'],
608 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
610 ['A list of holds for the stated library to pull for', 'array']
612 method => 'hold_pull_list',
615 sub find_optional_surveys {
620 return undef unless ($ou);
621 my $s_table = action::survey->table;
623 my $select = <<" SQL";
626 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
627 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
628 AND s.required IS FALSE;
631 my $sth = action::survey->db_Main->prepare_cached($select);
634 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
638 __PACKAGE__->register_method(
639 api_name => 'open-ils.storage.action.survey.optional',
642 method => 'find_optional_surveys',
645 sub find_required_surveys {
650 return undef unless ($ou);
651 my $s_table = action::survey->table;
653 my $select = <<" SQL";
656 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
657 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
658 AND s.required IS TRUE;
661 my $sth = action::survey->db_Main->prepare_cached($select);
664 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
668 __PACKAGE__->register_method(
669 api_name => 'open-ils.storage.action.survey.required',
672 method => 'find_required_surveys',
675 sub find_usr_summary_surveys {
680 return undef unless ($ou);
681 my $s_table = action::survey->table;
683 my $select = <<" SQL";
686 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
687 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
688 AND s.usr_summary IS TRUE;
691 my $sth = action::survey->db_Main->prepare_cached($select);
694 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
698 __PACKAGE__->register_method(
699 api_name => 'open-ils.storage.action.survey.usr_summary',
702 method => 'find_usr_summary_surveys',
705 sub seconds_to_interval_hash {
706 my $interval = shift;
707 my $limit = shift || 's';
708 $limit =~ s/^(.)/$1/o;
712 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
713 my ($year, $month, $week, $day, $hour, $minute, $second) =
714 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
716 if ($y = int($interval / (60 * 60 * 24 * 365))) {
718 $ym = $interval % (60 * 60 * 24 * 365);
722 return %output if ($limit eq 'y');
724 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
725 $output{$month} = $M;
726 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
730 return %output if ($limit eq 'M');
732 if ($w = int($Mm / 604800)) {
738 return %output if ($limit eq 'w');
740 if ($d = int($wm / 86400)) {
746 return %output if ($limit eq 'd');
748 if ($h = int($dm / 3600)) {
754 return %output if ($limit eq 'h');
756 if ($m = int($hm / 60)) {
757 $output{$minute} = $m;
762 return %output if ($limit eq 'm');
765 $output{$second} = $s;
767 $output{$second} = 0 unless (keys %output);
777 my $overbill = shift;
779 local $OpenILS::Application::Storage::WRITE = 1;
784 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
785 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
787 push @circs, overdue_circs();
790 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
792 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
796 $ctype =~ s/^.+::(\w+)$/$1/;
798 my $due_date_method = 'due_date';
799 my $target_copy_method = 'target_copy';
800 my $circ_lib_method = 'circ_lib';
801 my $recurring_fine_method = 'recurring_fine';
802 my $is_reservation = 0;
803 if ($ctype eq 'reservation') {
805 $due_date_method = 'end_time';
806 $target_copy_method = 'current_resource';
807 $circ_lib_method = 'pickup_lib';
808 $recurring_fine_method = 'fine_amount';
809 next unless ($c->fine_interval);
811 #TODO: reservation grace periods
812 my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
815 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
816 $log->debug("Cleaning up after previous transaction\n");
817 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
819 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
821 sprintf("Processing %s %d...",
822 ($is_reservation ? "reservation" : "circ"), $c->id
827 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
829 my $due = $due_dt->epoch;
832 my $fine_interval = $c->fine_interval;
833 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
834 $fine_interval = interval_to_seconds( $fine_interval );
836 if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
837 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
838 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
842 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
844 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
845 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
848 $due -= ($due % $fine_interval) + $tz_offset_s;
849 $now -= ($now % $fine_interval) + $tz_offset_s;
853 "ARG! Overdue $ctype ".$c->id.
854 " for item ".$c->$target_copy_method.
855 " (user ".$c->usr.").\n".
856 "\tItem was due on or before: ".localtime($due)."\n");
858 my @fines = money::billing->search_where(
861 billing_ts => { '>' => $c->$due_date_method } },
862 { order_by => 'billing_ts DESC'}
866 my $fine = $fines[$f_idx] if (@fines);
868 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
871 my $current_fine_total = 0;
872 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
876 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
877 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
879 $log->info( "Potential first billing for circ ".$c->id );
882 $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});
885 next if ($last_fine > $now);
886 # Generate fines for each past interval, including the one we are inside
887 my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
889 if ( $last_fine == $due # we have no fines yet
890 && $grace_period # and we have a grace period
891 && $now < $due + $grace_period # and some date math says were are within the grace period
893 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
894 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
898 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
899 next unless ($pending_fine_count);
901 my $recurring_fine = int($c->$recurring_fine_method * 100);
902 my $max_fine = int($c->max_fine * 100);
904 my ($latest_billing_ts, $latest_amount) = ('',0);
905 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
907 if ($current_fine_total >= $max_fine) {
908 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
910 "\tMaximum fine level of ".$c->max_fine.
911 " reached for this $ctype.\n".
912 "\tNo more fines will be generated.\n" );
916 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
917 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
918 my $current_bill_count = $bill;
919 while ( $current_bill_count ) {
920 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
921 $current_bill_count--;
924 my $dow = $billing_ts->day_of_week_0();
925 my $dow_open = "dow_${dow}_open";
926 my $dow_close = "dow_${dow}_close";
928 if (my $h = $hoo{$c->$circ_lib_method}) {
929 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
932 my $timestamptz = $billing_ts->strftime('%FT%T%z');
933 my @cl = actor::org_unit::closed_date->search_where(
934 { close_start => { '<=' => $timestamptz },
935 close_end => { '>=' => $timestamptz },
936 org_unit => $c->$circ_lib_method }
940 $current_fine_total += $recurring_fine;
941 $latest_amount += $recurring_fine;
942 $latest_billing_ts = $timestamptz;
944 money::billing->create(
946 note => "System Generated Overdue Fine",
947 billing_type => "Overdue materials",
949 amount => sprintf('%0.2f', $recurring_fine/100),
950 billing_ts => $timestamptz,
956 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
957 if ($latest_billing_ts and $latest_amount);
959 $self->method_lookup('open-ils.storage.transaction.commit')->run;
963 # Caluclate penalties inline
964 OpenILS::Utils::Penalty->calculate_penalties(
965 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
969 # Calculate penalties with an aysnc call to the penalty server. This approach
970 # may lead to duplicate penalties since multiple penalty processes for a
971 # given user may be running at the same time. Leave this here for reference
972 # in case we later find that asyc calls are needed in some environments.
974 'open-ils.penalty.patron_penalty.calculate',
975 { patronid => ''.$c->usr,
976 context_org => ''.$c->$circ_lib_method,
985 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
986 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
987 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
988 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
992 __PACKAGE__->register_method(
993 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
996 method => 'generate_fines',
1001 sub new_hold_copy_targeter {
1004 my $check_expire = shift;
1005 my $one_hold = shift;
1006 my $find_copy = shift;
1008 local $OpenILS::Application::Storage::WRITE = 1;
1010 $self->{target_weight} = {};
1011 $self->{max_loops} = {};
1017 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1018 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
1019 } elsif ( $check_expire ) {
1021 # what's the retarget time threashold?
1023 $check_expire ||= '12h';
1024 $check_expire = interval_to_seconds( $check_expire );
1026 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1029 my $expire_threshold = sprintf(
1030 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1031 $year, $mon, $mday, $hour, $min, $sec
1034 # find all the holds holds needing retargeting
1035 $holds = [ action::hold_request->search_where(
1036 { capture_time => undef,
1037 fulfillment_time => undef,
1038 cancel_time => undef,
1040 prev_check_time => { '<=' => $expire_threshold },
1042 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
1044 # find all the holds holds needing first time targeting
1045 push @$holds, action::hold_request->search(
1046 capture_time => undef,
1047 fulfillment_time => undef,
1048 prev_check_time => undef,
1050 cancel_time => undef,
1051 { order_by => 'selection_depth DESC, request_time' } );
1054 # find all the holds holds needing first time targeting ONLY
1055 $holds = [ action::hold_request->search(
1056 capture_time => undef,
1057 fulfillment_time => undef,
1058 prev_check_time => undef,
1059 cancel_time => undef,
1061 { order_by => 'selection_depth DESC, request_time' } ) ];
1063 } catch Error with {
1065 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1068 my @closed = actor::org_unit::closed_date->search_where(
1069 { close_start => { '<=', 'now' },
1070 close_end => { '>=', 'now' } }
1073 if ($check_expire) {
1075 # $check_expire, if it exists, was already converted to seconds
1076 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1080 my $next_check_time = sprintf(
1081 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1082 $year, $mon, $mday, $hour, $min, $sec
1086 my @closed_at_next = actor::org_unit::closed_date->search_where(
1087 { close_start => { '<=', $next_check_time },
1088 close_end => { '>=', $next_check_time } }
1092 for my $c_at_n (@closed_at_next) {
1093 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1094 push @new_closed, $c_at_n;
1097 @closed = @new_closed;
1101 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1103 my $target_when_closed = {};
1104 my $target_when_closed_if_at_pickup_lib = {};
1106 for my $hold (@$holds) {
1108 #start a transaction if needed
1109 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1110 $log->debug("Cleaning up after previous transaction\n");
1111 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1113 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1114 $log->info("Processing hold ".$hold->id."...\n");
1116 #first, re-fetch the hold, to make sure it's not captured already
1117 $hold->remove_from_object_index();
1118 $hold = action::hold_request->retrieve( $hold->id );
1120 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1122 # remove old auto-targeting maps
1123 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1124 $_->delete for (@oldmaps);
1126 if ($hold->expire_time) {
1127 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1128 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1130 # cancel cause = un-targeted expiration
1131 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1132 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1134 # tell A/T the hold was cancelled
1135 my $fm_hold = $hold->to_fieldmapper;
1136 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1137 $ses->request('open-ils.trigger.event.autocreate',
1138 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1144 my $all_copies = [];
1146 # find filters for MR holds
1147 my ($types, $formats, $lang);
1148 if (defined($hold->holdable_formats)) {
1149 ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1152 # find all the potential copies
1153 if ($hold->hold_type eq 'M') {
1156 isTrue($_->deleted) ? () : ($_->id)
1157 } metabib::metarecord->retrieve($hold->target)->source_records
1162 metabib::record_descriptor
1165 ( $types ? (item_type => [split '', $types]) : () ),
1166 ( $formats ? (item_form => [split '', $formats]) : () ),
1167 ( $lang ? (item_lang => $lang) : () ),
1171 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1172 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1174 for my $cn ( @{ $rtree->call_numbers } ) {
1176 asset::copy->search_where(
1177 { id => [map {$_->id} @{ $cn->copies }],
1179 ) if ($cn && @{ $cn->copies });
1183 } elsif ($hold->hold_type eq 'T') {
1185 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1186 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1189 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1193 for my $cn ( @{ $rtree->call_numbers } ) {
1195 asset::copy->search_where(
1196 { id => [map {$_->id} @{ $cn->copies }],
1198 ) if ($cn && @{ $cn->copies });
1200 } elsif ($hold->hold_type eq 'V') {
1202 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1203 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1206 asset::copy->search_where(
1207 { id => [map {$_->id} @{ $vtree->copies }],
1209 ) if ($vtree && @{ $vtree->copies });
1211 } elsif ($hold->hold_type eq 'P') {
1212 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1214 asset::copy->search_where(
1215 { id => [map {$_->target_copy} @part_maps],
1220 } elsif ($hold->hold_type eq 'I') {
1222 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1223 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1226 asset::copy->search_where(
1227 { id => [map {$_->unit->id} @{ $itree->items }],
1229 ) if ($itree && @{ $itree->items });
1231 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1232 my $_cp = asset::copy->retrieve($hold->target);
1233 push @$all_copies, $_cp if $_cp;
1236 # Force and recall holds bypass pretty much everything
1237 if ($hold->hold_type ne 'R' && $hold->hold_type ne 'F') {
1239 @$all_copies = grep { isTrue($_->status->holdable) &&
1240 isTrue($_->location->holdable) &&
1241 isTrue($_->holdable) &&
1242 !isTrue($_->deleted) &&
1243 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1244 ($hold->hold_type ne 'P' ? $_->part_maps->count == 0 : 1)
1248 # let 'em know we're still working
1249 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1251 # if we have no copies ...
1252 if (!ref $all_copies || !@$all_copies) {
1253 $log->info("\tNo copies available for targeting at all!\n");
1254 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1256 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1257 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1261 my $copy_count = @$all_copies;
1262 my $found_copy = undef;
1263 $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1265 # map the potentials, so that we can pick up checkins
1266 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1267 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1268 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1269 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1271 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1274 for my $c (@$all_copies) {
1276 next if ($c->id eq $hold->current_copy);
1278 # skip on circ lib is closed IFF we care
1281 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1282 $ignore_closing = ou_ancestor_setting_value_or_cache(
1285 'circ.holds.target_when_closed_if_at_pickup_lib',
1286 $target_when_closed_if_at_pickup_lib
1289 if (not $ignore_closing) { # one more chance to find a reason
1290 # to ignore OU closedness.
1291 $ignore_closing = ou_ancestor_setting_value_or_cache(
1294 'circ.holds.target_when_closed',
1300 # "For hold " . $hold->id . " and copy with circ_lib " .
1301 # $c->circ_lib . " we " .
1302 # ($ignore_closing ? "ignore" : "respect")
1307 (not $ignore_closing) and
1308 (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1311 # target of another hold
1312 next if (action::hold_request
1314 { current_copy => $c->id,
1315 fulfillment_time => undef,
1316 cancel_time => undef,
1321 # we passed all three, keep it
1322 push @good_copies, $c if ($c);
1323 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1326 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1328 my $old_best = $hold->current_copy;
1329 $hold->update({ current_copy => undef }) if ($old_best);
1331 if (!scalar(@good_copies)) {
1332 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1333 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1334 # the old copy is still available
1335 $log->debug("\tPushing current_copy back onto the targeting list");
1336 push @good_copies, $old_best;
1338 # oops, old copy is not available
1339 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1340 $hold->update( { prev_check_time => 'today' } );
1341 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1342 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1347 my $pu_lib = ''.$hold->pickup_lib;
1353 ''.$_->circ_lib eq $pu_lib &&
1354 ( $_->status == 0 || $_->status == 7 )
1358 $all_copies = [grep { $_->status == 0 || $_->status == 7 } grep {''.$_->circ_lib ne $pu_lib } @good_copies];
1359 # $all_copies is now a list of copies not at the pickup library
1362 if ($hold->hold_type eq 'R' || $hold->hold_type eq 'F') { # Recall/Force holds bypass hold rules.
1363 $best = $good_copies[0] if(scalar @good_copies);
1365 $best = choose_nearest_copy($hold, $prox_list);
1367 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1370 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1372 $self->{max_loops}{$pu_lib} = $actor->request(
1373 'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1376 if (defined($self->{max_loops}{$pu_lib})) {
1377 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1379 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1380 my $circ_lib_list = [keys %circ_lib_map];
1382 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1384 # Grab the "biggest" loop for this hold so far
1385 my $current_loop = $cstore->request(
1386 'open-ils.cstore.json_query',
1388 select => { aufhmxl => ['max'] },
1390 where => { hold => $hold->id}
1394 $current_loop = $current_loop->{max} if ($current_loop);
1395 $current_loop ||= 1;
1397 my $exclude_list = $cstore->request(
1398 'open-ils.cstore.json_query.atomic',
1400 select => { aufhol => ['circ_lib'] },
1402 where => { hold => $hold->id}
1407 if ($exclude_list && @$exclude_list) {
1408 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1409 # check to see if we've used up every library in the potentials list
1410 for my $l ( @$circ_lib_list ) {
1412 for my $ex ( @$exclude_list ) {
1418 push(@keepers, $l) if ($keep);
1421 @keepers = @$circ_lib_list;
1424 $current_loop++ if (!@keepers);
1426 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1427 # We haven't exceeded max_loops yet
1429 for my $cp ( @$all_copies ) {
1430 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1433 $all_copies = [@keeper_copies];
1435 # We have, and should remove potentials and cancel the hold
1436 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1437 $_->delete for (@oldmaps);
1439 # cancel cause = un-targeted expiration
1440 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1441 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1443 # tell A/T the hold was cancelled
1444 my $fm_hold = $hold->to_fieldmapper;
1445 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1446 $ses->request('open-ils.trigger.event.autocreate',
1447 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1453 $prox_list = create_prox_list( $self, $pu_lib, $all_copies );
1455 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1457 $best = choose_nearest_copy($hold, $prox_list);
1460 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1462 # hold wasn't fulfilled, record the fact
1464 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1465 action::unfulfilled_hold_list->create(
1466 { hold => ''.$hold->id,
1467 current_copy => ''.$old_best->id,
1468 circ_lib => ''.$old_best->circ_lib,
1473 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1474 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1477 !action::hold_request
1479 { current_copy => $old_best->id,
1480 fulfillment_time => undef,
1481 cancel_time => undef,
1485 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1486 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1488 $hold->update( { prev_check_time => 'now' } );
1489 $log->info( "\tThere were no targetable copies for the hold" );
1490 process_recall($actor, $log, $hold, \@good_copies);
1493 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1494 $log->info("\tProcessing of hold ".$hold->id." complete.");
1497 { hold => $hold->id,
1498 old_target => ($old_best ? $old_best->id : undef),
1499 eligible_copies => $copy_count,
1500 target => ($best ? $best->id : undef),
1501 found_copy => $found_copy };
1506 $log->error("Processing of hold failed: $e");
1507 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1508 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1515 __PACKAGE__->register_method(
1516 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1518 method => 'new_hold_copy_targeter',
1521 sub process_recall {
1522 my ($actor, $log, $hold, $good_copies) = @_;
1524 # Bail early if we don't have required settings to avoid spurious requests
1525 my ($recall_threshold, $return_interval, $fine_rules);
1527 my $rv = $actor->request(
1528 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1532 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1535 $recall_threshold = $rv->{value};
1537 $rv = $actor->request(
1538 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1542 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1545 $return_interval = $rv->{value};
1547 $rv = $actor->request(
1548 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1552 $fine_rules = $rv->{value};
1555 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1557 # We want checked out copies (status = 1) at the hold pickup lib
1558 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1560 my @copy_ids = map { $_->id } @$all_copies;
1562 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1564 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1566 # Iterate over the checked-out copies to find a copy with a
1567 # loan period longer than the recall threshold:
1568 my $circs = [ action::circulation->search_where(
1569 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1570 { order_by => 'due_date ASC' }
1573 # If we have a candidate copy, then:
1574 if (scalar(@$circs)) {
1575 my $circ = $circs->[0];
1576 $log->info("Recalling circ ID : " . $circ->id);
1578 # Give the user a new due date of either a full recall threshold,
1579 # or the return interval, whichever is further in the future
1580 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1581 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1582 $return_date = $threshold_date;
1585 my $update_fields = {
1586 due_date => $return_date,
1587 renewal_remaining => 0,
1590 # If the OU hasn't defined new fine rules for recalls, keep them
1593 $log->info("Apply recall fine rules: $fine_rules");
1594 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1595 $update_fields->{recurring_fine} = $rules->[0];
1596 $update_fields->{fine_interval} = $rules->[1];
1597 $update_fields->{max_fine} = $rules->[2];
1600 # Adjust circ for current user
1601 $circ->update($update_fields);
1603 # Create trigger event for notifying current user
1604 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1605 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1608 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1611 sub reservation_targeter {
1614 my $one_reservation = shift;
1616 local $OpenILS::Application::Storage::WRITE = 1;
1621 if ($one_reservation) {
1622 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1623 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1626 # find all the reservations needing targeting
1628 booking::reservation->search_where(
1629 { current_resource => undef,
1630 cancel_time => undef,
1631 start_time => { '>' => 'now' }
1633 { order_by => 'start_time' }
1637 } catch Error with {
1639 die "Could not retrieve reservation requests:\n\n$e\n";
1643 for my $bresv (@$reservations) {
1645 #start a transaction if needed
1646 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1647 $log->debug("Cleaning up after previous transaction\n");
1648 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1650 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1651 $log->info("Processing reservation ".$bresv->id."...\n");
1653 #first, re-fetch the hold, to make sure it's not captured already
1654 $bresv->remove_from_object_index();
1655 $bresv = booking::reservation->retrieve( $bresv->id );
1657 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1659 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1660 if (DateTime->compare($end_time, DateTime->now) < 0) {
1662 # cancel cause = un-targeted expiration
1663 $bresv->update( { cancel_time => 'now' } );
1664 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1666 # tell A/T the reservation was cancelled
1667 my $fm_bresv = $bresv->to_fieldmapper;
1668 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1669 $ses->request('open-ils.trigger.event.autocreate',
1670 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1675 my $possible_resources;
1677 # find all the potential resources
1678 if (!$bresv->target_resource) {
1679 my $filter = { type => $bresv->target_resource_type };
1680 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1682 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1684 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1685 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1686 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1688 $possible_resources = $bresv->target_resource;
1691 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1692 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1695 my @good_resources = ();
1697 for my $res (@$all_resources) {
1698 unless (isTrue($res->type->catalog_item)) {
1699 push @good_resources, $res;
1703 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1706 push @good_resources, $res;
1710 # At this point, if we're just targeting one specific
1711 # resource, just succeed. We don't care about its present
1713 if ($bresv->target_resource) {
1714 push @good_resources, $res;
1718 if ($copy->status->id == 0 || $copy->status->id == 7) {
1719 push @good_resources, $res;
1723 if ($copy->status->id == 1) {
1724 my $circs = [ action::circulation->search_where(
1725 {target_copy => $copy->id, checkin_time => undef },
1726 { order_by => 'id DESC' }
1730 my $due_date = $circs->[0]->due_date;
1731 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1732 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1733 if (DateTime->compare($start_time, $due_date) < 0) {
1734 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1738 push @good_resources, $res;
1744 push @good_resources, $res if (isTrue($copy->status->holdable));
1747 # let 'em know we're still working
1748 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1750 # if we have no copies ...
1751 if (!@good_resources) {
1752 $log->info("\tNo resources available for targeting at all!\n");
1753 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1756 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1760 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1766 $_->owner == $bresv->pickup_lib
1770 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1771 # $all_copies is now a list of copies not at the pickup library
1773 my $best = shift @good_resources;
1774 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1777 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1781 sort { $a->[0] <=> $b->[0] }
1783 [ actor::org_unit_proximity->search_where(
1784 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1790 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1792 $best = shift @$prox_list
1796 $bresv->update( { current_resource => ''.$best->id } );
1797 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1800 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1801 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1804 { reservation => $bresv->id,
1805 current_resource => ($best ? $best->id : undef) };
1810 $log->error("Processing of bresv failed: $e");
1811 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1812 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1819 __PACKAGE__->register_method(
1820 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1822 method => 'reservation_targeter',
1827 my %cache = (titles => {}, cns => {});
1829 sub copy_hold_capture {
1834 if (!defined($cps)) {
1836 $cps = [ asset::copy->search( id => $hold->target ) ];
1837 } catch Error with {
1839 die "Could not retrieve initial volume list:\n\n$e\n";
1843 my @copies = grep { $_->holdable } @$cps;
1845 for (my $i = 0; $i < @$cps; $i++) {
1846 next unless $$cps[$i];
1848 my $cn = $cache{cns}{$copies[$i]->call_number};
1849 my $rec = $cache{titles}{$cn->record};
1850 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1851 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1852 $copies[$i] = undef if (
1854 !$self->{user_filter}->request(
1855 'open-ils.circ.permit_hold',
1856 $hold->to_fieldmapper, do {
1857 my $cp_fm = $copies[$i]->to_fieldmapper;
1858 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1859 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1860 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1863 { title => $rec->to_fieldmapper,
1864 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1865 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1868 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1871 @copies = grep { $_ } @copies;
1873 my $count = @copies;
1875 return unless ($count);
1877 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1880 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1881 for my $c (@copies) {
1882 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1884 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1890 sub choose_nearest_copy {
1892 my $prox_list = shift;
1894 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1895 next unless (ref $$prox_list[$p]);
1897 my @capturable = @{ $$prox_list[$p] };
1898 next unless (@capturable);
1900 my $rand = int(rand(scalar(@capturable)));
1902 while (my ($c) = splice(@capturable, $rand, 1)) {
1903 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
1904 { title => $c->call_number->record->to_fieldmapper,
1905 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1906 patron => $hold->usr->to_fieldmapper,
1907 copy => $c->to_fieldmapper,
1908 requestor => $hold->requestor->to_fieldmapper,
1909 request_lib => $hold->request_lib->to_fieldmapper,
1910 pickup_lib => $hold->pickup_lib->id,
1916 last unless(@capturable);
1917 $rand = int(rand(scalar(@capturable)));
1922 sub create_prox_list {
1927 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1930 for my $cp (@$copies) {
1931 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1932 next unless (defined($prox));
1934 my $copy_circ_lib = ''.$cp->circ_lib;
1935 # Fetch the weighting value for hold targeting, defaulting to 1
1936 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
1937 'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
1939 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
1940 $self->{target_weight}{$copy_circ_lib} ||= 1;
1942 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1943 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
1944 push @{$prox_list[$prox]}, $cp;
1950 sub volume_hold_capture {
1955 if (!defined($vols)) {
1957 $vols = [ asset::call_number->search( id => $hold->target ) ];
1958 $cache{cns}{$_->id} = $_ for (@$vols);
1959 } catch Error with {
1961 die "Could not retrieve initial volume list:\n\n$e\n";
1965 my @v_ids = map { $_->id } @$vols;
1969 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1971 } catch Error with {
1973 warn "Could not retrieve copy list:\n\n$e\n";
1976 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1979 sub title_hold_capture {
1984 if (!defined($titles)) {
1986 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1987 $cache{titles}{$_->id} = $_ for (@$titles);
1988 } catch Error with {
1990 die "Could not retrieve initial title list:\n\n$e\n";
1994 my @t_ids = map { $_->id } @$titles;
1997 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1999 } catch Error with {
2001 warn "Could not retrieve volume list:\n\n$e\n";
2004 $cache{cns}{$_->id} = $_ for (@$cn_list);
2006 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
2009 sub metarecord_hold_capture {
2015 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
2017 } catch Error with {
2019 die "Could not retrieve initial title list:\n\n$e\n";
2023 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
2025 $titles = [ biblio::record_entry->search( id => \@recs ) ];
2027 } catch Error with {
2029 die "Could not retrieve format-pruned title list:\n\n$e\n";
2033 $cache{titles}{$_->id} = $_ for (@$titles);
2034 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);