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 $cp = asset::copy->table;
173 LEFT JOIN $setting setting
174 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
176 AND cp.status_changed_time < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
179 my $sth = action::circulation->db_Main->prepare_cached($sql);
180 $sth->execute($window, $window, $window);
185 __PACKAGE__->register_method(
186 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
189 method => 'complete_reshelving',
192 sub mark_longoverdue {
197 local $OpenILS::Application::Storage::WRITE = 1;
199 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
200 unless (interval_to_seconds( $window ));
202 my $setting = actor::org_unit_setting->table;
203 my $circ = action::circulation->table;
207 SET stop_fines = 'LONGOVERDUE',
208 stop_fines_time = now()
212 LEFT JOIN $setting setting
213 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
214 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
215 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
219 my $sth = action::circulation->db_Main->prepare_cached($sql);
220 $sth->execute($window);
225 __PACKAGE__->register_method(
226 api_name => 'open-ils.storage.action.circulation.long_overdue',
229 method => 'mark_longoverdue',
232 sub auto_thaw_frozen_holds {
236 local $OpenILS::Application::Storage::WRITE = 1;
238 my $holds = action::hold_request->table;
240 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
242 my $sth = action::hold_request->db_Main->prepare_cached($sql);
248 __PACKAGE__->register_method(
249 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
253 method => 'auto_thaw_frozen_holds',
260 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
262 $client->respond( $idlist ? $_ : $_->to_fieldmapper ) for ( overdue_circs('', $idlist) );
267 __PACKAGE__->register_method(
268 api_name => 'open-ils.storage.action.circulation.overdue',
271 method => 'grab_overdue',
273 Return list of overdue circulations and reservations to be used for fine generation.
274 Despite the name, this is not a generic method for retrieving all overdue loans,
275 as it excludes loans that have already hit the maximum fine limit.
278 __PACKAGE__->register_method(
279 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
282 method => 'grab_overdue',
290 my $limit = int(shift()) || 10;
291 my $age = shift() || '0 seconds';
294 local $OpenILS::Application::Storage::WRITE = 1;
296 my $holdsort = isTrue($fifo) ?
297 "pgt.hold_priority, CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END, h.request_time, h.selection_depth DESC, p.prox " :
298 "p.prox, pgt.hold_priority, CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END, h.selection_depth DESC, h.request_time ";
300 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
302 FROM action.hold_request h
303 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
304 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
305 JOIN actor.usr au ON (au.id = h.usr)
306 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
307 WHERE hm.target_copy = ?
308 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
309 AND h.capture_time IS NULL
310 AND h.cancel_time IS NULL
311 AND (h.expire_time IS NULL OR h.expire_time > NOW())
312 AND h.frozen IS FALSE
317 $client->respond( $_ ) for ( @$ids );
320 __PACKAGE__->register_method(
321 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
324 method => 'nearest_hold',
327 sub targetable_holds {
330 my $check_expire = shift;
332 $check_expire ||= '12h';
334 local $OpenILS::Application::Storage::WRITE = 1;
336 # json_query can *almost* represent this query, but can't
337 # handle the CASE statement or the interval arithmetic
338 my $query = <<" SQL";
339 SELECT ahr.id, mmsm.metarecord
340 FROM action.hold_request ahr
341 JOIN reporter.hold_request_record USING (id)
342 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
343 WHERE capture_time IS NULL
344 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
345 AND fulfillment_time IS NULL
346 AND cancel_time IS NULL
348 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
350 my $sth = action::hold_request->db_Main->prepare_cached($query);
351 $sth->execute($check_expire);
353 $client->respond( $_ ) for ( $sth->fetchall_arrayref );
357 __PACKAGE__->register_method(
358 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
361 method => 'targetable_holds',
363 Returns ordered list of hold request and metarecord IDs
364 for all hold requests that are available for initial targeting
366 @param check interval
367 @return list of pairs of hold request and metarecord IDs
371 sub next_resp_group_id {
375 # XXX This is not replication safe!!!
377 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
378 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
382 __PACKAGE__->register_method(
383 api_name => 'open-ils.storage.action.survey_response.next_group_id',
385 method => 'next_resp_group_id',
388 sub patron_circ_summary {
393 return undef unless ($id);
394 my $c_table = action::circulation->table;
395 my $b_table = money::billing->table;
397 $log->debug("Retrieving patron summary for id $id", DEBUG);
399 my $select = <<" SQL";
400 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
402 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
404 AND c.xact_finish IS NULL
406 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
407 OR c.stop_fines IS NULL
411 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
413 __PACKAGE__->register_method(
414 api_name => 'open-ils.storage.action.circulation.patron_summary',
416 method => 'patron_circ_summary',
419 #XXX Fix stored proc calls
420 sub find_local_surveys {
425 return undef unless ($ou);
426 my $s_table = action::survey->table;
428 my $select = <<" SQL";
431 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
432 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
435 my $sth = action::survey->db_Main->prepare_cached($select);
438 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
442 __PACKAGE__->register_method(
443 api_name => 'open-ils.storage.action.survey.all',
446 method => 'find_local_surveys',
449 #XXX Fix stored proc calls
450 sub find_opac_surveys {
455 return undef unless ($ou);
456 my $s_table = action::survey->table;
458 my $select = <<" SQL";
461 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
462 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
466 my $sth = action::survey->db_Main->prepare_cached($select);
469 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
473 __PACKAGE__->register_method(
474 api_name => 'open-ils.storage.action.survey.opac',
477 method => 'find_opac_surveys',
484 my $limit = shift || 10;
485 my $offset = shift || 0;
487 return undef unless ($ou);
488 my $h_table = action::hold_request->table;
489 my $a_table = asset::copy->table;
490 my $ord_table = asset::copy_location_order->table;
492 my $idlist = 1 if ($self->api_name =~/id_list/o);
493 my $count = 1 if ($self->api_name =~/count$/o);
495 my $status_filter = '';
496 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
498 my $select = <<" SQL";
501 JOIN $a_table a ON (h.current_copy = a.id)
502 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
504 AND h.capture_time IS NULL
505 AND h.cancel_time IS NULL
506 AND (h.expire_time IS NULL OR h.expire_time > NOW())
508 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
517 JOIN $a_table a ON (h.current_copy = a.id)
519 AND h.capture_time IS NULL
520 AND h.cancel_time IS NULL
521 AND (h.expire_time IS NULL OR h.expire_time > NOW())
526 my $sth = action::survey->db_Main->prepare_cached($select);
530 $client->respond( $sth->fetchall_arrayref()->[0][0] );
532 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
534 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
539 __PACKAGE__->register_method(
540 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
544 "Returns a count of holds for a specific library's pull list.",
545 [ [org_unit => "The library's org id", "number"] ],
546 ['A count of holds for the stated library to pull ', 'number']
548 method => 'hold_pull_list',
550 __PACKAGE__->register_method(
551 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
555 "Returns a status filtered count of holds for a specific library's pull list.",
556 [ [org_unit => "The library's org id", "number"] ],
557 ['A status filtered count of holds for the stated library to pull ', 'number']
559 method => 'hold_pull_list',
561 __PACKAGE__->register_method(
562 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
566 "Returns the hold ids for a specific library's pull list.",
567 [ [org_unit => "The library's org id", "number"],
568 [limit => 'An optional page size, defaults to 10', 'number'],
569 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
571 ['A list of holds for the stated library to pull for', 'array']
573 method => 'hold_pull_list',
575 __PACKAGE__->register_method(
576 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
580 "Returns the holds for a specific library's pull list.",
581 [ [org_unit => "The library's org id", "number"],
582 [limit => 'An optional page size, defaults to 10', 'number'],
583 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
585 ['A list of holds for the stated library to pull for', 'array']
587 method => 'hold_pull_list',
589 __PACKAGE__->register_method(
590 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
594 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
595 [ [org_unit => "The library's org id", "number"],
596 [limit => 'An optional page size, defaults to 10', 'number'],
597 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
599 ['A list of holds for the stated library to pull for', 'array']
601 method => 'hold_pull_list',
603 __PACKAGE__->register_method(
604 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
608 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
609 [ [org_unit => "The library's org id", "number"],
610 [limit => 'An optional page size, defaults to 10', 'number'],
611 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
613 ['A list of holds for the stated library to pull for', 'array']
615 method => 'hold_pull_list',
618 sub find_optional_surveys {
623 return undef unless ($ou);
624 my $s_table = action::survey->table;
626 my $select = <<" SQL";
629 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
630 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
631 AND s.required IS FALSE;
634 my $sth = action::survey->db_Main->prepare_cached($select);
637 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
641 __PACKAGE__->register_method(
642 api_name => 'open-ils.storage.action.survey.optional',
645 method => 'find_optional_surveys',
648 sub find_required_surveys {
653 return undef unless ($ou);
654 my $s_table = action::survey->table;
656 my $select = <<" SQL";
659 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
660 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
661 AND s.required IS TRUE;
664 my $sth = action::survey->db_Main->prepare_cached($select);
667 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
671 __PACKAGE__->register_method(
672 api_name => 'open-ils.storage.action.survey.required',
675 method => 'find_required_surveys',
678 sub find_usr_summary_surveys {
683 return undef unless ($ou);
684 my $s_table = action::survey->table;
686 my $select = <<" SQL";
689 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
690 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
691 AND s.usr_summary IS TRUE;
694 my $sth = action::survey->db_Main->prepare_cached($select);
697 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
701 __PACKAGE__->register_method(
702 api_name => 'open-ils.storage.action.survey.usr_summary',
705 method => 'find_usr_summary_surveys',
708 sub seconds_to_interval_hash {
709 my $interval = shift;
710 my $limit = shift || 's';
711 $limit =~ s/^(.)/$1/o;
715 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
716 my ($year, $month, $week, $day, $hour, $minute, $second) =
717 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
719 if ($y = int($interval / (60 * 60 * 24 * 365))) {
721 $ym = $interval % (60 * 60 * 24 * 365);
725 return %output if ($limit eq 'y');
727 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
728 $output{$month} = $M;
729 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
733 return %output if ($limit eq 'M');
735 if ($w = int($Mm / 604800)) {
741 return %output if ($limit eq 'w');
743 if ($d = int($wm / 86400)) {
749 return %output if ($limit eq 'd');
751 if ($h = int($dm / 3600)) {
757 return %output if ($limit eq 'h');
759 if ($m = int($hm / 60)) {
760 $output{$minute} = $m;
765 return %output if ($limit eq 'm');
768 $output{$second} = $s;
770 $output{$second} = 0 unless (keys %output);
780 my $overbill = shift;
782 local $OpenILS::Application::Storage::WRITE = 1;
787 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
788 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
790 push @circs, overdue_circs();
793 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
795 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
799 $ctype =~ s/^.+::(\w+)$/$1/;
801 my $due_date_method = 'due_date';
802 my $target_copy_method = 'target_copy';
803 my $circ_lib_method = 'circ_lib';
804 my $recurring_fine_method = 'recurring_fine';
805 my $is_reservation = 0;
806 if ($ctype eq 'reservation') {
808 $due_date_method = 'end_time';
809 $target_copy_method = 'current_resource';
810 $circ_lib_method = 'pickup_lib';
811 $recurring_fine_method = 'fine_amount';
812 next unless ($c->fine_interval);
814 #TODO: reservation grace periods
815 my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
818 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
819 $log->debug("Cleaning up after previous transaction\n");
820 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
822 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
824 sprintf("Processing %s %d...",
825 ($is_reservation ? "reservation" : "circ"), $c->id
830 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
832 my $due = $due_dt->epoch;
835 my $fine_interval = $c->fine_interval;
836 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
837 $fine_interval = interval_to_seconds( $fine_interval );
839 if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
840 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
841 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
845 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
847 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
848 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
851 $due -= ($due % $fine_interval) + $tz_offset_s;
852 $now -= ($now % $fine_interval) + $tz_offset_s;
856 "ARG! Overdue $ctype ".$c->id.
857 " for item ".$c->$target_copy_method.
858 " (user ".$c->usr.").\n".
859 "\tItem was due on or before: ".localtime($due)."\n");
861 my @fines = money::billing->search_where(
864 billing_ts => { '>' => $c->$due_date_method } },
865 { order_by => 'billing_ts DESC'}
869 my $fine = $fines[$f_idx] if (@fines);
871 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
874 my $current_fine_total = 0;
875 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
879 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
880 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
882 $log->info( "Potential first billing for circ ".$c->id );
885 $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});
888 next if ($last_fine > $now);
889 # Generate fines for each past interval, including the one we are inside
890 my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
892 if ( $last_fine == $due # we have no fines yet
893 && $grace_period # and we have a grace period
894 && $now < $due + $grace_period # and some date math says were are within the grace period
896 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
897 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
901 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
902 next unless ($pending_fine_count);
904 my $recurring_fine = int($c->$recurring_fine_method * 100);
905 my $max_fine = int($c->max_fine * 100);
907 my ($latest_billing_ts, $latest_amount) = ('',0);
908 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
910 if ($current_fine_total >= $max_fine) {
911 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
913 "\tMaximum fine level of ".$c->max_fine.
914 " reached for this $ctype.\n".
915 "\tNo more fines will be generated.\n" );
919 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
920 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
921 my $current_bill_count = $bill;
922 while ( $current_bill_count ) {
923 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
924 $current_bill_count--;
927 my $dow = $billing_ts->day_of_week_0();
928 my $dow_open = "dow_${dow}_open";
929 my $dow_close = "dow_${dow}_close";
931 if (my $h = $hoo{$c->$circ_lib_method}) {
932 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
935 my $timestamptz = $billing_ts->strftime('%FT%T%z');
936 my @cl = actor::org_unit::closed_date->search_where(
937 { close_start => { '<=' => $timestamptz },
938 close_end => { '>=' => $timestamptz },
939 org_unit => $c->$circ_lib_method }
943 $current_fine_total += $recurring_fine;
944 $latest_amount += $recurring_fine;
945 $latest_billing_ts = $timestamptz;
947 money::billing->create(
949 note => "System Generated Overdue Fine",
950 billing_type => "Overdue materials",
952 amount => sprintf('%0.2f', $recurring_fine/100),
953 billing_ts => $timestamptz,
959 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
960 if ($latest_billing_ts and $latest_amount);
962 $self->method_lookup('open-ils.storage.transaction.commit')->run;
966 # Caluclate penalties inline
967 OpenILS::Utils::Penalty->calculate_penalties(
968 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
972 # Calculate penalties with an aysnc call to the penalty server. This approach
973 # may lead to duplicate penalties since multiple penalty processes for a
974 # given user may be running at the same time. Leave this here for reference
975 # in case we later find that asyc calls are needed in some environments.
977 'open-ils.penalty.patron_penalty.calculate',
978 { patronid => ''.$c->usr,
979 context_org => ''.$c->$circ_lib_method,
988 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
989 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
990 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
991 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
995 __PACKAGE__->register_method(
996 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
999 method => 'generate_fines',
1004 sub new_hold_copy_targeter {
1007 my $check_expire = shift;
1008 my $one_hold = shift;
1009 my $find_copy = shift;
1011 local $OpenILS::Application::Storage::WRITE = 1;
1013 $self->{target_weight} = {};
1014 $self->{max_loops} = {};
1020 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1021 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef, frozen => 'f' } ) ];
1022 } elsif ( $check_expire ) {
1024 # what's the retarget time threashold?
1026 $check_expire ||= '12h';
1027 $check_expire = interval_to_seconds( $check_expire );
1029 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1032 my $expire_threshold = sprintf(
1033 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1034 $year, $mon, $mday, $hour, $min, $sec
1037 # find all the holds holds needing retargeting
1038 $holds = [ action::hold_request->search_where(
1039 { capture_time => undef,
1040 fulfillment_time => undef,
1041 cancel_time => undef,
1043 prev_check_time => { '<=' => $expire_threshold },
1045 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
1047 # find all the holds holds needing first time targeting
1048 push @$holds, action::hold_request->search(
1049 capture_time => undef,
1050 fulfillment_time => undef,
1051 prev_check_time => undef,
1053 cancel_time => undef,
1054 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
1057 # find all the holds holds needing first time targeting ONLY
1058 $holds = [ action::hold_request->search(
1059 capture_time => undef,
1060 fulfillment_time => undef,
1061 prev_check_time => undef,
1062 cancel_time => undef,
1064 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
1066 } catch Error with {
1068 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1071 my @closed = actor::org_unit::closed_date->search_where(
1072 { close_start => { '<=', 'now' },
1073 close_end => { '>=', 'now' } }
1076 if ($check_expire) {
1078 # $check_expire, if it exists, was already converted to seconds
1079 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1083 my $next_check_time = sprintf(
1084 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1085 $year, $mon, $mday, $hour, $min, $sec
1089 my @closed_at_next = actor::org_unit::closed_date->search_where(
1090 { close_start => { '<=', $next_check_time },
1091 close_end => { '>=', $next_check_time } }
1095 for my $c_at_n (@closed_at_next) {
1096 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1097 push @new_closed, $c_at_n;
1100 @closed = @new_closed;
1104 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1106 my $target_when_closed = {};
1107 my $target_when_closed_if_at_pickup_lib = {};
1109 for my $hold (@$holds) {
1111 #start a transaction if needed
1112 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1113 $log->debug("Cleaning up after previous transaction\n");
1114 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1116 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1117 $log->info("Processing hold ".$hold->id."...\n");
1119 #first, re-fetch the hold, to make sure it's not captured already
1120 $hold->remove_from_object_index();
1121 $hold = action::hold_request->retrieve( $hold->id );
1123 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1125 # remove old auto-targeting maps
1126 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1127 $_->delete for (@oldmaps);
1129 if ($hold->expire_time) {
1130 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1131 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1133 # cancel cause = un-targeted expiration
1134 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1135 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1137 # tell A/T the hold was cancelled
1138 my $fm_hold = $hold->to_fieldmapper;
1139 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1140 $ses->request('open-ils.trigger.event.autocreate',
1141 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1147 my $all_copies = [];
1149 # find filters for MR holds
1150 my ($types, $formats, $lang);
1151 if (defined($hold->holdable_formats)) {
1152 ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1155 # find all the potential copies
1156 if ($hold->hold_type eq 'M') {
1159 metabib::record_descriptor
1163 isTrue($_->deleted) ? () : ($_->id)
1164 } metabib::metarecord->retrieve($hold->target)->source_records
1166 ( $types ? (item_type => [split '', $types]) : () ),
1167 ( $formats ? (item_form => [split '', $formats]) : () ),
1168 ( $lang ? (item_lang => $lang) : () ),
1172 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1173 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1175 for my $cn ( @{ $rtree->call_numbers } ) {
1177 asset::copy->search_where(
1178 { id => [map {$_->id} @{ $cn->copies }],
1180 ) 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;
1237 @$all_copies = grep { isTrue($_->status->holdable) &&
1238 isTrue($_->location->holdable) &&
1239 isTrue($_->holdable) &&
1240 !isTrue($_->deleted) &&
1241 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1242 ($hold->hold_type ne 'P' ? $_->part_maps->count == 0 : 1)
1245 # let 'em know we're still working
1246 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1248 # if we have no copies ...
1249 if (!ref $all_copies || !@$all_copies) {
1250 $log->info("\tNo copies available for targeting at all!\n");
1251 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1253 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1254 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1258 my $copy_count = @$all_copies;
1259 my $found_copy = undef;
1260 $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1262 # map the potentials, so that we can pick up checkins
1263 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1264 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1265 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1266 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1268 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1271 for my $c (@$all_copies) {
1273 next if ($c->id eq $hold->current_copy);
1275 # skip on circ lib is closed IFF we care
1278 if (''.$hold->pickup_lib eq ''.$c->circ_lib) {
1279 $ignore_closing = ou_ancestor_setting_value_or_cache(
1282 'circ.holds.target_when_closed_if_at_pickup_lib',
1283 $target_when_closed_if_at_pickup_lib
1286 if (not $ignore_closing) { # one more chance to find a reason
1287 # to ignore OU closedness.
1288 $ignore_closing = ou_ancestor_setting_value_or_cache(
1291 'circ.holds.target_when_closed',
1297 # "For hold " . $hold->id . " and copy with circ_lib " .
1298 # $c->circ_lib . " we " .
1299 # ($ignore_closing ? "ignore" : "respect")
1304 (not $ignore_closing) and
1305 (grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed)
1308 # target of another hold
1309 next if (action::hold_request
1311 { current_copy => $c->id,
1312 fulfillment_time => undef,
1313 cancel_time => undef,
1318 # we passed all three, keep it
1319 push @good_copies, $c if ($c);
1320 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1323 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1325 my $old_best = $hold->current_copy;
1326 $hold->update({ current_copy => undef }) if ($old_best);
1328 if (!scalar(@good_copies)) {
1329 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1330 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1331 # the old copy is still available
1332 $log->debug("\tPushing current_copy back onto the targeting list");
1333 push @good_copies, $old_best;
1335 # oops, old copy is not available
1336 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1337 $hold->update( { prev_check_time => 'today' } );
1338 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1339 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1344 my $pu_lib = ''.$hold->pickup_lib;
1350 ''.$_->circ_lib eq $pu_lib &&
1351 ( $_->status == 0 || $_->status == 7 )
1355 $all_copies = [grep { $_->status == 0 || $_->status == 7 } grep {''.$_->circ_lib ne $pu_lib } @good_copies];
1356 # $all_copies is now a list of copies not at the pickup library
1358 my $best = choose_nearest_copy($hold, $prox_list);
1359 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1362 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1364 $self->{max_loops}{$pu_lib} = $actor->request(
1365 'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1368 if (defined($self->{max_loops}{$pu_lib})) {
1369 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1371 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1372 my $circ_lib_list = [keys %circ_lib_map];
1374 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1376 # Grab the "biggest" loop for this hold so far
1377 my $current_loop = $cstore->request(
1378 'open-ils.cstore.json_query',
1380 select => { aufhmxl => ['max'] },
1382 where => { hold => $hold->id}
1386 $current_loop = $current_loop->{max} if ($current_loop);
1387 $current_loop ||= 1;
1389 my $exclude_list = $cstore->request(
1390 'open-ils.cstore.json_query.atomic',
1392 select => { aufhol => ['circ_lib'] },
1394 where => { hold => $hold->id}
1399 if ($exclude_list && @$exclude_list) {
1400 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1401 # check to see if we've used up every library in the potentials list
1402 for my $l ( @$circ_lib_list ) {
1404 for my $ex ( @$exclude_list ) {
1410 push(@keepers, $l) if ($keep);
1413 @keepers = @$circ_lib_list;
1416 $current_loop++ if (!@keepers);
1418 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1419 # We haven't exceeded max_loops yet
1421 for my $cp ( @$all_copies ) {
1422 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1425 $all_copies = [@keeper_copies];
1427 # We have, and should remove potentials and cancel the hold
1428 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1429 $_->delete for (@oldmaps);
1431 # cancel cause = un-targeted expiration
1432 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1433 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1435 # tell A/T the hold was cancelled
1436 my $fm_hold = $hold->to_fieldmapper;
1437 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1438 $ses->request('open-ils.trigger.event.autocreate',
1439 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1445 $prox_list = create_prox_list( $self, $pu_lib, $all_copies );
1447 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1449 $best = choose_nearest_copy($hold, $prox_list);
1452 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1454 # hold wasn't fulfilled, record the fact
1456 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1457 action::unfulfilled_hold_list->create(
1458 { hold => ''.$hold->id,
1459 current_copy => ''.$old_best->id,
1460 circ_lib => ''.$old_best->circ_lib,
1465 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1466 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1469 !action::hold_request
1471 { current_copy => $old_best->id,
1472 fulfillment_time => undef,
1473 cancel_time => undef,
1477 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1478 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1480 $hold->update( { prev_check_time => 'now' } );
1481 $log->info( "\tThere were no targetable copies for the hold" );
1482 process_recall($actor, $log, $hold, \@good_copies);
1485 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1486 $log->info("\tProcessing of hold ".$hold->id." complete.");
1489 { hold => $hold->id,
1490 old_target => ($old_best ? $old_best->id : undef),
1491 eligible_copies => $copy_count,
1492 target => ($best ? $best->id : undef),
1493 found_copy => $found_copy };
1498 $log->error("Processing of hold failed: $e");
1499 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1500 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1507 __PACKAGE__->register_method(
1508 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1510 method => 'new_hold_copy_targeter',
1513 sub process_recall {
1514 my ($actor, $log, $hold, $good_copies) = @_;
1516 # Bail early if we don't have required settings to avoid spurious requests
1517 my ($recall_threshold, $return_interval, $fine_rules);
1519 my $rv = $actor->request(
1520 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1524 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1527 $recall_threshold = $rv->{value};
1529 $rv = $actor->request(
1530 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1534 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1537 $return_interval = $rv->{value};
1539 $rv = $actor->request(
1540 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1544 $fine_rules = $rv->{value};
1547 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1549 # We want checked out copies (status = 1) at the hold pickup lib
1550 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1552 my @copy_ids = map { $_->id } @$all_copies;
1554 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1556 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1558 # Iterate over the checked-out copies to find a copy with a
1559 # loan period longer than the recall threshold:
1560 my $circs = [ action::circulation->search_where(
1561 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1562 { order_by => 'due_date ASC' }
1565 # If we have a candidate copy, then:
1566 if (scalar(@$circs)) {
1567 my $circ = $circs->[0];
1568 $log->info("Recalling circ ID : " . $circ->id);
1570 # Give the user a new due date of either a full recall threshold,
1571 # or the return interval, whichever is further in the future
1572 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1573 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1574 $return_date = $threshold_date;
1577 my $update_fields = {
1578 due_date => $return_date,
1579 renewal_remaining => 0,
1582 # If the OU hasn't defined new fine rules for recalls, keep them
1585 $log->info("Apply recall fine rules: $fine_rules");
1586 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1587 $update_fields->{recurring_fine} = $rules->[0];
1588 $update_fields->{fine_interval} = $rules->[1];
1589 $update_fields->{max_fine} = $rules->[2];
1592 # Adjust circ for current user
1593 $circ->update($update_fields);
1595 # Create trigger event for notifying current user
1596 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1597 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1600 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1603 sub reservation_targeter {
1606 my $one_reservation = shift;
1608 local $OpenILS::Application::Storage::WRITE = 1;
1613 if ($one_reservation) {
1614 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1615 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1618 # find all the reservations needing targeting
1620 booking::reservation->search_where(
1621 { current_resource => undef,
1622 cancel_time => undef,
1623 start_time => { '>' => 'now' }
1625 { order_by => 'start_time' }
1629 } catch Error with {
1631 die "Could not retrieve reservation requests:\n\n$e\n";
1635 for my $bresv (@$reservations) {
1637 #start a transaction if needed
1638 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1639 $log->debug("Cleaning up after previous transaction\n");
1640 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1642 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1643 $log->info("Processing reservation ".$bresv->id."...\n");
1645 #first, re-fetch the hold, to make sure it's not captured already
1646 $bresv->remove_from_object_index();
1647 $bresv = booking::reservation->retrieve( $bresv->id );
1649 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1651 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1652 if (DateTime->compare($end_time, DateTime->now) < 0) {
1654 # cancel cause = un-targeted expiration
1655 $bresv->update( { cancel_time => 'now' } );
1656 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1658 # tell A/T the reservation was cancelled
1659 my $fm_bresv = $bresv->to_fieldmapper;
1660 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1661 $ses->request('open-ils.trigger.event.autocreate',
1662 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1667 my $possible_resources;
1669 # find all the potential resources
1670 if (!$bresv->target_resource) {
1671 my $filter = { type => $bresv->target_resource_type };
1672 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1674 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1676 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1677 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1678 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1680 $possible_resources = $bresv->target_resource;
1683 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1684 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1687 my @good_resources = ();
1689 for my $res (@$all_resources) {
1690 unless (isTrue($res->type->catalog_item)) {
1691 push @good_resources, $res;
1695 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1698 push @good_resources, $res;
1702 # At this point, if we're just targeting one specific
1703 # resource, just succeed. We don't care about its present
1705 if ($bresv->target_resource) {
1706 push @good_resources, $res;
1710 if ($copy->status->id == 0 || $copy->status->id == 7) {
1711 push @good_resources, $res;
1715 if ($copy->status->id == 1) {
1716 my $circs = [ action::circulation->search_where(
1717 {target_copy => $copy->id, checkin_time => undef },
1718 { order_by => 'id DESC' }
1722 my $due_date = $circs->[0]->due_date;
1723 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1724 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1725 if (DateTime->compare($start_time, $due_date) < 0) {
1726 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1730 push @good_resources, $res;
1736 push @good_resources, $res if (isTrue($copy->status->holdable));
1739 # let 'em know we're still working
1740 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1742 # if we have no copies ...
1743 if (!@good_resources) {
1744 $log->info("\tNo resources available for targeting at all!\n");
1745 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1748 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1752 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1758 $_->owner == $bresv->pickup_lib
1762 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1763 # $all_copies is now a list of copies not at the pickup library
1765 my $best = shift @good_resources;
1766 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1769 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1773 sort { $a->[0] <=> $b->[0] }
1775 [ actor::org_unit_proximity->search_where(
1776 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1782 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1784 $best = shift @$prox_list
1788 $bresv->update( { current_resource => ''.$best->id } );
1789 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1792 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1793 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1796 { reservation => $bresv->id,
1797 current_resource => ($best ? $best->id : undef) };
1802 $log->error("Processing of bresv failed: $e");
1803 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1804 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1811 __PACKAGE__->register_method(
1812 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1814 method => 'reservation_targeter',
1819 my %cache = (titles => {}, cns => {});
1821 sub copy_hold_capture {
1826 if (!defined($cps)) {
1828 $cps = [ asset::copy->search( id => $hold->target ) ];
1829 } catch Error with {
1831 die "Could not retrieve initial volume list:\n\n$e\n";
1835 my @copies = grep { $_->holdable } @$cps;
1837 for (my $i = 0; $i < @$cps; $i++) {
1838 next unless $$cps[$i];
1840 my $cn = $cache{cns}{$copies[$i]->call_number};
1841 my $rec = $cache{titles}{$cn->record};
1842 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1843 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1844 $copies[$i] = undef if (
1846 !$self->{user_filter}->request(
1847 'open-ils.circ.permit_hold',
1848 $hold->to_fieldmapper, do {
1849 my $cp_fm = $copies[$i]->to_fieldmapper;
1850 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1851 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1852 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1855 { title => $rec->to_fieldmapper,
1856 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1857 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1860 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1863 @copies = grep { $_ } @copies;
1865 my $count = @copies;
1867 return unless ($count);
1869 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1872 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1873 for my $c (@copies) {
1874 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1876 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1882 sub choose_nearest_copy {
1884 my $prox_list = shift;
1886 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1887 next unless (ref $$prox_list[$p]);
1889 my @capturable = @{ $$prox_list[$p] };
1890 next unless (@capturable);
1892 my $rand = int(rand(scalar(@capturable)));
1894 while (my ($c) = splice(@capturable, $rand, 1)) {
1895 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
1896 { title => $c->call_number->record->to_fieldmapper,
1897 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1898 patron => $hold->usr->to_fieldmapper,
1899 copy => $c->to_fieldmapper,
1900 requestor => $hold->requestor->to_fieldmapper,
1901 request_lib => $hold->request_lib->to_fieldmapper,
1902 pickup_lib => $hold->pickup_lib->id,
1908 last unless(@capturable);
1909 $rand = int(rand(scalar(@capturable)));
1914 sub create_prox_list {
1919 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1922 for my $cp (@$copies) {
1923 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1924 next unless (defined($prox));
1926 my $copy_circ_lib = ''.$cp->circ_lib;
1927 # Fetch the weighting value for hold targeting, defaulting to 1
1928 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
1929 'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
1931 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
1932 $self->{target_weight}{$copy_circ_lib} ||= 1;
1934 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1935 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
1936 push @{$prox_list[$prox]}, $cp;
1942 sub volume_hold_capture {
1947 if (!defined($vols)) {
1949 $vols = [ asset::call_number->search( id => $hold->target ) ];
1950 $cache{cns}{$_->id} = $_ for (@$vols);
1951 } catch Error with {
1953 die "Could not retrieve initial volume list:\n\n$e\n";
1957 my @v_ids = map { $_->id } @$vols;
1961 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1963 } catch Error with {
1965 warn "Could not retrieve copy list:\n\n$e\n";
1968 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1971 sub title_hold_capture {
1976 if (!defined($titles)) {
1978 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1979 $cache{titles}{$_->id} = $_ for (@$titles);
1980 } catch Error with {
1982 die "Could not retrieve initial title list:\n\n$e\n";
1986 my @t_ids = map { $_->id } @$titles;
1989 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1991 } catch Error with {
1993 warn "Could not retrieve volume list:\n\n$e\n";
1996 $cache{cns}{$_->id} = $_ for (@$cn_list);
1998 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
2001 sub metarecord_hold_capture {
2007 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
2009 } catch Error with {
2011 die "Could not retrieve initial title list:\n\n$e\n";
2015 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
2017 $titles = [ biblio::record_entry->search( id => \@recs ) ];
2019 } catch Error with {
2021 die "Could not retrieve format-pruned title list:\n\n$e\n";
2025 $cache{titles}{$_->id} = $_ for (@$titles);
2026 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);