1 package OpenILS::Application::Storage::Publisher::action;
2 use parent qw/OpenILS::Application::Storage::Publisher/;
5 use OpenSRF::Utils::Logger qw/:level/;
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;
18 return 1 if ($v == 1);
19 return 1 if ($v =~ /^t/io);
20 return 1 if ($v =~ /^y/io);
24 my $parser = DateTime::Format::ISO8601->new;
25 my $log = 'OpenSRF::Utils::Logger';
27 sub open_noncat_circs {
32 my $a = action::non_cataloged_circulation->table;
33 my $c = config::non_cataloged_type->table;
38 JOIN $c c ON (a.item_type = c.id)
39 WHERE a.circ_time + c.circ_duration > current_timestamp
43 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
45 __PACKAGE__->register_method(
46 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
47 method => 'open_noncat_circs',
53 sub ou_hold_requests {
58 my $h_table = action::hold_request->table;
59 my $c_table = asset::copy->table;
60 my $o_table = actor::org_unit->table;
65 JOIN $c_table cp ON (cp.id = h.current_copy)
66 JOIN $o_table ou ON (ou.id = cp.circ_lib)
68 AND h.capture_time IS NULL
69 AND h.cancel_time IS NULL
70 AND (h.expire_time IS NULL OR h.expire_time > NOW())
71 ORDER BY h.request_time
74 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
77 $client->respond($_) for (
80 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
84 } @{ $sth->fetchall_arrayref }
88 __PACKAGE__->register_method(
89 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
93 method => 'ou_hold_requests',
99 my $upper_interval = shift || '1 millennium';
102 my $c_t = action::circulation->table;
104 if ($grace && $grace =~ /^\d+$/o) {
105 $grace = " - ($grace * (fine_interval))";
113 WHERE stop_fines IS NULL
114 AND due_date < ( CURRENT_TIMESTAMP $grace)
115 AND fine_interval < ?::INTERVAL
118 my $sth = action::circulation->db_Main->prepare_cached($sql);
119 $sth->execute($upper_interval);
121 my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
123 $c_t = booking::reservation->table;
127 WHERE return_time IS NULL
128 AND end_time < ( CURRENT_TIMESTAMP $grace)
129 AND fine_interval IS NOT NULL
130 AND cancel_time IS NULL
133 $sth = action::circulation->db_Main->prepare_cached($sql);
136 push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
141 sub complete_reshelving {
146 local $OpenILS::Application::Storage::WRITE = 1;
148 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
149 unless (interval_to_seconds( $window ));
151 my $setting = actor::org_unit_setting->table;
152 my $circ = action::circulation->table;
153 my $cp = asset::copy->table;
154 my $atc = action::transit_copy->table;
161 FROM (SELECT cp.id, MAX(circ.checkin_time), MAX(trans.dest_recv_time)
163 JOIN $circ circ ON (circ.target_copy = cp.id)
164 LEFT JOIN $atc trans ON (trans.target_copy = cp.id)
165 LEFT JOIN $setting setting
166 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
167 WHERE circ.checkin_time IS NOT NULL
171 ( ( MAX(circ.checkin_time) > MAX(trans.dest_recv_time) or MAX(trans.dest_recv_time) IS NULL )
172 AND MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
174 ( MAX(trans.dest_recv_time) > MAX(circ.checkin_time)
175 AND MAX(trans.dest_recv_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
181 LEFT JOIN $setting setting
182 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
183 LEFT JOIN $circ circ ON (circ.target_copy = cp.id)
186 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
189 my $sth = action::circulation->db_Main->prepare_cached($sql);
190 $sth->execute($window, $window, $window);
195 __PACKAGE__->register_method(
196 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
199 method => 'complete_reshelving',
202 sub mark_longoverdue {
207 local $OpenILS::Application::Storage::WRITE = 1;
209 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
210 unless (interval_to_seconds( $window ));
212 my $setting = actor::org_unit_setting->table;
213 my $circ = action::circulation->table;
217 SET stop_fines = 'LONGOVERDUE',
218 stop_fines_time = now()
222 LEFT JOIN $setting setting
223 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
224 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
225 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
229 my $sth = action::circulation->db_Main->prepare_cached($sql);
230 $sth->execute($window);
235 __PACKAGE__->register_method(
236 api_name => 'open-ils.storage.action.circulation.long_overdue',
239 method => 'mark_longoverdue',
242 sub auto_thaw_frozen_holds {
246 local $OpenILS::Application::Storage::WRITE = 1;
248 my $holds = action::hold_request->table;
250 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
252 my $sth = action::hold_request->db_Main->prepare_cached($sql);
258 __PACKAGE__->register_method(
259 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
263 method => 'auto_thaw_frozen_holds',
269 my $grace = shift || '';
271 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
273 $client->respond( $idlist ? $_ : $_->to_fieldmapper ) for ( overdue_circs($grace, '', $idlist) );
278 __PACKAGE__->register_method(
279 api_name => 'open-ils.storage.action.circulation.overdue',
282 method => 'grab_overdue',
284 Return list of overdue circulations and reservations to be used for fine generation.
285 Despite the name, this is not a generic method for retrieving all overdue loans,
286 as it excludes loans that have already hit the maximum fine limit.
289 __PACKAGE__->register_method(
290 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
293 method => 'grab_overdue',
301 my $limit = int(shift()) || 10;
302 my $age = shift() || '0 seconds';
305 local $OpenILS::Application::Storage::WRITE = 1;
307 my $holdsort = isTrue($fifo) ?
308 "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 " :
309 "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 ";
311 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
313 FROM action.hold_request h
314 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
315 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
316 JOIN actor.usr au ON (au.id = h.usr)
317 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
318 WHERE hm.target_copy = ?
319 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
320 AND h.capture_time IS NULL
321 AND h.cancel_time IS NULL
322 AND (h.expire_time IS NULL OR h.expire_time > NOW())
323 AND h.frozen IS FALSE
328 $client->respond( $_ ) for ( @$ids );
331 __PACKAGE__->register_method(
332 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
335 method => 'nearest_hold',
338 sub targetable_holds {
341 my $check_expire = shift;
343 $check_expire ||= '12h';
345 local $OpenILS::Application::Storage::WRITE = 1;
347 # json_query can *almost* represent this query, but can't
348 # handle the CASE statement or the interval arithmetic
349 my $query = <<" SQL";
350 SELECT ahr.id, mmsm.metarecord
351 FROM action.hold_request ahr
352 JOIN reporter.hold_request_record USING (id)
353 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
354 WHERE capture_time IS NULL
355 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
356 AND fulfillment_time IS NULL
357 AND cancel_time IS NULL
359 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
361 my $sth = action::hold_request->db_Main->prepare_cached($query);
362 $sth->execute($check_expire);
364 $client->respond( $_ ) for ( $sth->fetchall_arrayref );
368 __PACKAGE__->register_method(
369 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
372 method => 'targetable_holds',
374 Returns ordered list of hold request and metarecord IDs
375 for all hold requests that are available for initial targeting
377 @param check interval
378 @return list of pairs of hold request and metarecord IDs
382 sub next_resp_group_id {
386 # XXX This is not replication safe!!!
388 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
389 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
393 __PACKAGE__->register_method(
394 api_name => 'open-ils.storage.action.survey_response.next_group_id',
396 method => 'next_resp_group_id',
399 sub patron_circ_summary {
404 return undef unless ($id);
405 my $c_table = action::circulation->table;
406 my $b_table = money::billing->table;
408 $log->debug("Retrieving patron summary for id $id", DEBUG);
410 my $select = <<" SQL";
411 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
413 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
415 AND c.xact_finish IS NULL
417 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
418 OR c.stop_fines IS NULL
422 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
424 __PACKAGE__->register_method(
425 api_name => 'open-ils.storage.action.circulation.patron_summary',
427 method => 'patron_circ_summary',
430 #XXX Fix stored proc calls
431 sub find_local_surveys {
436 return undef unless ($ou);
437 my $s_table = action::survey->table;
439 my $select = <<" SQL";
442 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
443 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
446 my $sth = action::survey->db_Main->prepare_cached($select);
449 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
453 __PACKAGE__->register_method(
454 api_name => 'open-ils.storage.action.survey.all',
457 method => 'find_local_surveys',
460 #XXX Fix stored proc calls
461 sub find_opac_surveys {
466 return undef unless ($ou);
467 my $s_table = action::survey->table;
469 my $select = <<" SQL";
472 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
473 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
477 my $sth = action::survey->db_Main->prepare_cached($select);
480 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
484 __PACKAGE__->register_method(
485 api_name => 'open-ils.storage.action.survey.opac',
488 method => 'find_opac_surveys',
495 my $limit = shift || 10;
496 my $offset = shift || 0;
498 return undef unless ($ou);
499 my $h_table = action::hold_request->table;
500 my $a_table = asset::copy->table;
501 my $ord_table = asset::copy_location_order->table;
503 my $idlist = 1 if ($self->api_name =~/id_list/o);
504 my $count = 1 if ($self->api_name =~/count$/o);
506 my $status_filter = '';
507 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
509 my $select = <<" SQL";
512 JOIN $a_table a ON (h.current_copy = a.id)
513 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
515 AND h.capture_time IS NULL
516 AND h.cancel_time IS NULL
517 AND (h.expire_time IS NULL OR h.expire_time > NOW())
519 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
528 JOIN $a_table a ON (h.current_copy = a.id)
530 AND h.capture_time IS NULL
531 AND h.cancel_time IS NULL
532 AND (h.expire_time IS NULL OR h.expire_time > NOW())
537 my $sth = action::survey->db_Main->prepare_cached($select);
541 $client->respond( $sth->fetchall_arrayref()->[0][0] );
543 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
545 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
550 __PACKAGE__->register_method(
551 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
555 "Returns a count of holds for a specific library's pull list.",
556 [ [org_unit => "The library's org id", "number"] ],
557 ['A 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.current_copy_circ_lib.status_filtered.count',
566 "Returns a status filtered count of holds for a specific library's pull list.",
567 [ [org_unit => "The library's org id", "number"] ],
568 ['A status filtered count of holds for the stated library to pull ', 'number']
570 method => 'hold_pull_list',
572 __PACKAGE__->register_method(
573 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
577 "Returns the hold ids 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.search.current_copy_circ_lib',
591 "Returns the holds for a specific library's pull list.",
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.id_list.current_copy_circ_lib.status_filtered',
605 "Returns the hold ids 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',
614 __PACKAGE__->register_method(
615 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
619 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
620 [ [org_unit => "The library's org id", "number"],
621 [limit => 'An optional page size, defaults to 10', 'number'],
622 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
624 ['A list of holds for the stated library to pull for', 'array']
626 method => 'hold_pull_list',
629 sub find_optional_surveys {
634 return undef unless ($ou);
635 my $s_table = action::survey->table;
637 my $select = <<" SQL";
640 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
641 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
642 AND s.required IS FALSE;
645 my $sth = action::survey->db_Main->prepare_cached($select);
648 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
652 __PACKAGE__->register_method(
653 api_name => 'open-ils.storage.action.survey.optional',
656 method => 'find_optional_surveys',
659 sub find_required_surveys {
664 return undef unless ($ou);
665 my $s_table = action::survey->table;
667 my $select = <<" SQL";
670 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
671 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
672 AND s.required IS TRUE;
675 my $sth = action::survey->db_Main->prepare_cached($select);
678 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
682 __PACKAGE__->register_method(
683 api_name => 'open-ils.storage.action.survey.required',
686 method => 'find_required_surveys',
689 sub find_usr_summary_surveys {
694 return undef unless ($ou);
695 my $s_table = action::survey->table;
697 my $select = <<" SQL";
700 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
701 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
702 AND s.usr_summary IS TRUE;
705 my $sth = action::survey->db_Main->prepare_cached($select);
708 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
712 __PACKAGE__->register_method(
713 api_name => 'open-ils.storage.action.survey.usr_summary',
716 method => 'find_usr_summary_surveys',
719 sub seconds_to_interval_hash {
720 my $interval = shift;
721 my $limit = shift || 's';
722 $limit =~ s/^(.)/$1/o;
726 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
727 my ($year, $month, $week, $day, $hour, $minute, $second) =
728 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
730 if ($y = int($interval / (60 * 60 * 24 * 365))) {
732 $ym = $interval % (60 * 60 * 24 * 365);
736 return %output if ($limit eq 'y');
738 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
739 $output{$month} = $M;
740 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
744 return %output if ($limit eq 'M');
746 if ($w = int($Mm / 604800)) {
752 return %output if ($limit eq 'w');
754 if ($d = int($wm / 86400)) {
760 return %output if ($limit eq 'd');
762 if ($h = int($dm / 3600)) {
768 return %output if ($limit eq 'h');
770 if ($m = int($hm / 60)) {
771 $output{$minute} = $m;
776 return %output if ($limit eq 'm');
779 $output{$second} = $s;
781 $output{$second} = 0 unless (keys %output);
792 my $overbill = shift;
794 local $OpenILS::Application::Storage::WRITE = 1;
799 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
800 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
802 push @circs, overdue_circs($grace);
805 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
807 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
811 $ctype =~ s/^.+::(\w+)$/$1/;
813 my $due_date_method = 'due_date';
814 my $target_copy_method = 'target_copy';
815 my $circ_lib_method = 'circ_lib';
816 my $recurring_fine_method = 'recurring_fine';
817 my $is_reservation = 0;
818 if ($ctype eq 'reservation') {
820 $due_date_method = 'end_time';
821 $target_copy_method = 'current_resource';
822 $circ_lib_method = 'pickup_lib';
823 $recurring_fine_method = 'fine_amount';
824 next unless ($c->fine_interval);
828 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
829 $log->debug("Cleaning up after previous transaction\n");
830 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
832 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
834 sprintf("Processing %s %d...",
835 ($is_reservation ? "reservation" : "circ"), $c->id
840 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
842 my $due = $due_dt->epoch;
845 my $fine_interval = $c->fine_interval;
846 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
847 $fine_interval = interval_to_seconds( $fine_interval );
849 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
851 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
852 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
855 $due -= ($due % $fine_interval) + $tz_offset_s;
856 $now -= ($now % $fine_interval) + $tz_offset_s;
860 "ARG! Overdue $ctype ".$c->id.
861 " for item ".$c->$target_copy_method.
862 " (user ".$c->usr.").\n".
863 "\tItem was due on or before: ".localtime($due)."\n");
865 my @fines = money::billing->search_where(
868 billing_ts => { '>' => $c->$due_date_method } },
869 { order_by => 'billing_ts DESC'}
873 my $fine = $fines[$f_idx] if (@fines);
875 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
878 my $current_fine_total = 0;
879 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
883 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
884 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
886 $log->info( "Potential first billing for circ ".$c->id );
890 if (my $h = $hoo{$c->$circ_lib_method}) {
892 $log->info( "Circ lib has an hours-of-operation entry" );
893 # find the day after the due date...
894 $due_dt = $due_dt->add( days => 1 );
896 # get the day of the week for that day...
897 my $dow = $due_dt->day_of_week_0;
898 my $dow_open = "dow_${dow}_open";
899 my $dow_close = "dow_${dow}_close";
902 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
903 # if the circ lib is closed, add a day to the grace period...
906 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
907 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
909 $due_dt = $due_dt->add( days => 1 );
910 $dow = $due_dt->day_of_week_0;
911 $dow_open = "dow_${dow}_open";
912 $dow_close = "dow_${dow}_close";
916 # and check for up to a week
917 last if ($count > 6);
923 next if ($last_fine > $now);
924 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
926 # Generate fines for the interval we are currently inside, when the fine interval is some multiple of 1d
927 $pending_fine_count++ if ($fine_interval && ($fine_interval % 86400 == 0));
929 if ( $last_fine == $due # we have no fines yet
930 && $grace # and we have a grace period
931 && $pending_fine_count <= $grace # and we seem to be inside that period
932 && $now < $due + $fine_interval * $grace # and some date math bares that out, then
934 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
935 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
939 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
940 next unless ($pending_fine_count);
942 my $recurring_fine = int($c->$recurring_fine_method * 100);
943 my $max_fine = int($c->max_fine * 100);
945 my ($latest_billing_ts, $latest_amount) = ('',0);
946 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
948 if ($current_fine_total >= $max_fine) {
949 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
951 "\tMaximum fine level of ".$c->max_fine.
952 " reached for this $ctype.\n".
953 "\tNo more fines will be generated.\n" );
957 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
958 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
959 my $current_bill_count = $bill;
960 while ( $current_bill_count ) {
961 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
962 $current_bill_count--;
965 my $dow = $billing_ts->day_of_week_0();
966 my $dow_open = "dow_${dow}_open";
967 my $dow_close = "dow_${dow}_close";
969 if (my $h = $hoo{$c->$circ_lib_method}) {
970 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
973 my $timestamptz = $billing_ts->strftime('%FT%T%z');
974 my @cl = actor::org_unit::closed_date->search_where(
975 { close_start => { '<=' => $timestamptz },
976 close_end => { '>=' => $timestamptz },
977 org_unit => $c->$circ_lib_method }
981 $current_fine_total += $recurring_fine;
982 $latest_amount += $recurring_fine;
983 $latest_billing_ts = $timestamptz;
985 money::billing->create(
987 note => "System Generated Overdue Fine",
988 billing_type => "Overdue materials",
990 amount => sprintf('%0.2f', $recurring_fine/100),
991 billing_ts => $timestamptz,
997 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
998 if ($latest_billing_ts and $latest_amount);
1000 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1004 # Caluclate penalties inline
1005 OpenILS::Utils::Penalty->calculate_penalties(
1006 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
1010 # Calculate penalties with an aysnc call to the penalty server. This approach
1011 # may lead to duplicate penalties since multiple penalty processes for a
1012 # given user may be running at the same time. Leave this here for reference
1013 # in case we later find that asyc calls are needed in some environments.
1015 'open-ils.penalty.patron_penalty.calculate',
1016 { patronid => ''.$c->usr,
1017 context_org => ''.$c->$circ_lib_method,
1024 } catch Error with {
1026 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
1027 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
1028 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1029 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1033 __PACKAGE__->register_method(
1034 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1037 method => 'generate_fines',
1042 sub new_hold_copy_targeter {
1045 my $check_expire = shift;
1046 my $one_hold = shift;
1048 local $OpenILS::Application::Storage::WRITE = 1;
1050 $self->{target_weight} = {};
1051 $self->{max_loops} = {};
1057 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1058 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
1059 } elsif ( $check_expire ) {
1061 # what's the retarget time threashold?
1063 $check_expire ||= '12h';
1064 $check_expire = interval_to_seconds( $check_expire );
1066 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1069 my $expire_threshold = sprintf(
1070 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1071 $year, $mon, $mday, $hour, $min, $sec
1074 # find all the holds holds needing retargeting
1075 $holds = [ action::hold_request->search_where(
1076 { capture_time => undef,
1077 fulfillment_time => undef,
1078 cancel_time => undef,
1080 prev_check_time => { '<=' => $expire_threshold },
1082 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
1084 # find all the holds holds needing first time targeting
1085 push @$holds, action::hold_request->search(
1086 capture_time => undef,
1087 fulfillment_time => undef,
1088 prev_check_time => undef,
1090 cancel_time => undef,
1091 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
1094 # find all the holds holds needing first time targeting ONLY
1095 $holds = [ action::hold_request->search(
1096 capture_time => undef,
1097 fulfillment_time => undef,
1098 prev_check_time => undef,
1099 cancel_time => undef,
1101 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
1103 } catch Error with {
1105 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1108 my @closed = actor::org_unit::closed_date->search_where(
1109 { close_start => { '<=', 'now' },
1110 close_end => { '>=', 'now' } }
1113 if ($check_expire) {
1115 # $check_expire, if it exists, was already converted to seconds
1116 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1120 my $next_check_time = sprintf(
1121 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1122 $year, $mon, $mday, $hour, $min, $sec
1126 my @closed_at_next = actor::org_unit::closed_date->search_where(
1127 { close_start => { '<=', $next_check_time },
1128 close_end => { '>=', $next_check_time } }
1132 for my $c_at_n (@closed_at_next) {
1133 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1134 push @new_closed, $c_at_n;
1137 @closed = @new_closed;
1141 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1143 for my $hold (@$holds) {
1145 #start a transaction if needed
1146 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1147 $log->debug("Cleaning up after previous transaction\n");
1148 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1150 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1151 $log->info("Processing hold ".$hold->id."...\n");
1153 #first, re-fetch the hold, to make sure it's not captured already
1154 $hold->remove_from_object_index();
1155 $hold = action::hold_request->retrieve( $hold->id );
1157 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1159 # remove old auto-targeting maps
1160 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1161 $_->delete for (@oldmaps);
1163 if ($hold->expire_time) {
1164 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1165 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1167 # cancel cause = un-targeted expiration
1168 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1169 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1171 # tell A/T the hold was cancelled
1172 my $fm_hold = $hold->to_fieldmapper;
1173 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1174 $ses->request('open-ils.trigger.event.autocreate',
1175 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1181 my $all_copies = [];
1183 # find filters for MR holds
1184 my ($types, $formats, $lang);
1185 if (defined($hold->holdable_formats)) {
1186 ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1189 # find all the potential copies
1190 if ($hold->hold_type eq 'M') {
1193 metabib::record_descriptor
1197 isTrue($_->deleted) ? () : ($_->id)
1198 } metabib::metarecord->retrieve($hold->target)->source_records
1200 ( $types ? (item_type => [split '', $types]) : () ),
1201 ( $formats ? (item_form => [split '', $formats]) : () ),
1202 ( $lang ? (item_lang => $lang) : () ),
1206 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1207 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1209 for my $cn ( @{ $rtree->call_numbers } ) {
1211 asset::copy->search_where(
1212 { id => [map {$_->id} @{ $cn->copies }],
1214 ) if ($cn && @{ $cn->copies });
1217 } elsif ($hold->hold_type eq 'T') {
1219 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1220 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1223 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1227 for my $cn ( @{ $rtree->call_numbers } ) {
1229 asset::copy->search_where(
1230 { id => [map {$_->id} @{ $cn->copies }],
1232 ) if ($cn && @{ $cn->copies });
1234 } elsif ($hold->hold_type eq 'V') {
1236 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1237 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1240 asset::copy->search_where(
1241 { id => [map {$_->id} @{ $vtree->copies }],
1243 ) if ($vtree && @{ $vtree->copies });
1245 } elsif ($hold->hold_type eq 'I') {
1247 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1248 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1251 asset::copy->search_where(
1252 { id => [map {$_->unit->id} @{ $itree->items }],
1254 ) if ($itree && @{ $itree->items });
1256 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1257 my $_cp = asset::copy->retrieve($hold->target);
1258 push @$all_copies, $_cp if $_cp;
1262 @$all_copies = grep { isTrue($_->status->holdable) &&
1263 isTrue($_->location->holdable) &&
1264 isTrue($_->holdable) &&
1265 !isTrue($_->deleted) &&
1266 isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1
1269 # let 'em know we're still working
1270 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1272 # if we have no copies ...
1273 if (!ref $all_copies || !@$all_copies) {
1274 $log->info("\tNo copies available for targeting at all!\n");
1275 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1277 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1278 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1282 my $copy_count = @$all_copies;
1284 # map the potentials, so that we can pick up checkins
1285 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1286 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1287 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1288 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1290 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1293 for my $c (@$all_copies) {
1295 next if ($c->id eq $hold->current_copy);
1297 # circ lib is closed
1298 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1300 # target of another hold
1301 next if (action::hold_request
1303 { current_copy => $c->id,
1304 fulfillment_time => undef,
1305 cancel_time => undef,
1310 # we passed all three, keep it
1311 push @good_copies, $c if ($c);
1312 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1315 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1317 my $old_best = $hold->current_copy;
1318 $hold->update({ current_copy => undef }) if ($old_best);
1320 if (!scalar(@good_copies)) {
1321 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1322 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1323 # the old copy is still available
1324 $log->debug("\tPushing current_copy back onto the targeting list");
1325 push @good_copies, $old_best;
1327 # oops, old copy is not available
1328 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1329 $hold->update( { prev_check_time => 'today' } );
1330 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1331 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1336 my $pu_lib = ''.$hold->pickup_lib;
1342 ''.$_->circ_lib eq $pu_lib &&
1343 ( $_->status == 0 || $_->status == 7 )
1347 $all_copies = [grep { $_->status == 0 || $_->status == 7 } grep {''.$_->circ_lib ne $pu_lib } @good_copies];
1348 # $all_copies is now a list of copies not at the pickup library
1350 my $best = choose_nearest_copy($hold, $prox_list);
1351 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1354 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1356 $self->{max_loops}{$pu_lib} = $actor->request(
1357 'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1360 if (defined($self->{max_loops}{$pu_lib})) {
1361 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1363 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1364 my $circ_lib_list = [keys %circ_lib_map];
1366 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1368 # Grab the "biggest" loop for this hold so far
1369 my $current_loop = $cstore->request(
1370 'open-ils.cstore.json_query',
1372 select => { aufhmxl => ['max'] },
1374 where => { hold => $hold->id}
1378 $current_loop = $current_loop->{max} if ($current_loop);
1379 $current_loop ||= 1;
1381 my $exclude_list = $cstore->request(
1382 'open-ils.cstore.json_query.atomic',
1384 select => { aufhol => ['circ_lib'] },
1386 where => { hold => $hold->id}
1391 if ($exclude_list && @$exclude_list) {
1392 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1393 # check to see if we've used up every library in the potentials list
1394 for my $l ( @$circ_lib_list ) {
1396 for my $ex ( @$exclude_list ) {
1402 push(@keepers, $l) if ($keep);
1405 @keepers = @$circ_lib_list;
1408 $current_loop++ if (!@keepers);
1410 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1411 # We haven't exceeded max_loops yet
1413 for my $cp ( @$all_copies ) {
1414 push(@keeper_copies, $cp) if ( grep { $_ eq ''.$cp->circ_lib } @keepers );
1416 $all_copies = [@keeper_copies];
1418 # We have, and should remove potentials and cancel the hold
1419 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1420 $_->delete for (@oldmaps);
1422 # cancel cause = un-targeted expiration
1423 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1424 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1426 # tell A/T the hold was cancelled
1427 my $fm_hold = $hold->to_fieldmapper;
1428 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1429 $ses->request('open-ils.trigger.event.autocreate',
1430 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1436 $prox_list = create_prox_list( $self, $pu_lib, $all_copies );
1438 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1440 $best = choose_nearest_copy($hold, $prox_list);
1443 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1445 # hold wasn't fulfilled, record the fact
1447 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1448 action::unfulfilled_hold_list->create(
1449 { hold => ''.$hold->id,
1450 current_copy => ''.$old_best->id,
1451 circ_lib => ''.$old_best->circ_lib,
1456 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1457 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1460 !action::hold_request
1462 { current_copy => $old_best->id,
1463 fulfillment_time => undef,
1464 cancel_time => undef,
1468 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1469 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1471 $hold->update( { prev_check_time => 'now' } );
1472 $log->info( "\tThere were no targetable copies for the hold" );
1473 process_recall($actor, $log, $hold, \@good_copies);
1476 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1477 $log->info("\tProcessing of hold ".$hold->id." complete.");
1480 { hold => $hold->id,
1481 old_target => ($old_best ? $old_best->id : undef),
1482 eligible_copies => $copy_count,
1483 target => ($best ? $best->id : undef) };
1488 $log->error("Processing of hold failed: $e");
1489 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1490 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1497 __PACKAGE__->register_method(
1498 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1500 method => 'new_hold_copy_targeter',
1503 sub process_recall {
1504 my ($actor, $log, $hold, $good_copies) = @_;
1506 # Bail early if we don't have required settings to avoid spurious requests
1507 my ($recall_threshold, $return_interval, $fine_rules);
1509 my $rv = $actor->request(
1510 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1514 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1517 $recall_threshold = $rv->{value};
1519 $rv = $actor->request(
1520 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1524 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1527 $return_interval = $rv->{value};
1529 $rv = $actor->request(
1530 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1534 $fine_rules = $rv->{value};
1537 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1539 # We want checked out copies (status = 1) at the hold pickup lib
1540 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1542 my @copy_ids = map { $_->id } @$all_copies;
1544 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1546 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1548 # Iterate over the checked-out copies to find a copy with a
1549 # loan period longer than the recall threshold:
1550 my $circs = [ action::circulation->search_where(
1551 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1552 { order_by => 'due_date ASC' }
1555 # If we have a candidate copy, then:
1556 if (scalar(@$circs)) {
1557 my $circ = $circs->[0];
1558 $log->info("Recalling circ ID : " . $circ->id);
1560 # Give the user a new due date of either a full recall threshold,
1561 # or the return interval, whichever is further in the future
1562 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1563 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1564 $return_date = $threshold_date;
1567 my $update_fields = {
1568 due_date => $return_date,
1569 renewal_remaining => 0,
1572 # If the OU hasn't defined new fine rules for recalls, keep them
1575 $log->info("Apply recall fine rules: $fine_rules");
1576 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1577 $update_fields->{recurring_fine} = $rules->[0];
1578 $update_fields->{fine_interval} = $rules->[1];
1579 $update_fields->{max_fine} = $rules->[2];
1582 # Adjust circ for current user
1583 $circ->update($update_fields);
1585 # Create trigger event for notifying current user
1586 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1587 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1590 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1593 sub reservation_targeter {
1596 my $one_reservation = shift;
1598 local $OpenILS::Application::Storage::WRITE = 1;
1603 if ($one_reservation) {
1604 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1605 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1608 # find all the reservations needing targeting
1610 booking::reservation->search_where(
1611 { current_resource => undef,
1612 cancel_time => undef,
1613 start_time => { '>' => 'now' }
1615 { order_by => 'start_time' }
1619 } catch Error with {
1621 die "Could not retrieve reservation requests:\n\n$e\n";
1625 for my $bresv (@$reservations) {
1627 #start a transaction if needed
1628 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1629 $log->debug("Cleaning up after previous transaction\n");
1630 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1632 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1633 $log->info("Processing reservation ".$bresv->id."...\n");
1635 #first, re-fetch the hold, to make sure it's not captured already
1636 $bresv->remove_from_object_index();
1637 $bresv = booking::reservation->retrieve( $bresv->id );
1639 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1641 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1642 if (DateTime->compare($end_time, DateTime->now) < 0) {
1644 # cancel cause = un-targeted expiration
1645 $bresv->update( { cancel_time => 'now' } );
1646 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1648 # tell A/T the reservation was cancelled
1649 my $fm_bresv = $bresv->to_fieldmapper;
1650 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1651 $ses->request('open-ils.trigger.event.autocreate',
1652 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1657 my $possible_resources;
1659 # find all the potential resources
1660 if (!$bresv->target_resource) {
1661 my $filter = { type => $bresv->target_resource_type };
1662 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1664 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1666 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1667 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1668 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1670 $possible_resources = $bresv->target_resource;
1673 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1674 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1677 my @good_resources = ();
1679 for my $res (@$all_resources) {
1680 unless (isTrue($res->type->catalog_item)) {
1681 push @good_resources, $res;
1685 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1688 push @good_resources, $res;
1692 if ($copy->status->id == 0 || $copy->status->id == 7) {
1693 push @good_resources, $res;
1697 if ($copy->status->id == 1) {
1698 my $circs = [ action::circulation->search_where(
1699 {target_copy => $copy->id, checkin_time => undef },
1700 { order_by => 'id DESC' }
1704 my $due_date = $circs->[0]->due_date;
1705 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1706 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1707 if (DateTime->compare($start_time, $due_date) < 0) {
1708 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1712 push @good_resources, $res;
1718 push @good_resources, $res if (isTrue($copy->status->holdable));
1721 # let 'em know we're still working
1722 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1724 # if we have no copies ...
1725 if (!@good_resources) {
1726 $log->info("\tNo resources available for targeting at all!\n");
1727 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1730 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1734 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1740 $_->owner == $bresv->pickup_lib
1744 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1745 # $all_copies is now a list of copies not at the pickup library
1747 my $best = shift @good_resources;
1748 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1751 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1755 sort { $a->[0] <=> $b->[0] }
1757 [ actor::org_unit_proximity->search_where(
1758 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1764 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1766 $best = shift @$prox_list
1770 $bresv->update( { current_resource => ''.$best->id } );
1771 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1774 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1775 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1778 { reservation => $bresv->id,
1779 current_resource => ($best ? $best->id : undef) };
1784 $log->error("Processing of bresv failed: $e");
1785 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1786 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1793 __PACKAGE__->register_method(
1794 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1796 method => 'reservation_targeter',
1801 my %cache = (titles => {}, cns => {});
1803 sub copy_hold_capture {
1808 if (!defined($cps)) {
1810 $cps = [ asset::copy->search( id => $hold->target ) ];
1811 } catch Error with {
1813 die "Could not retrieve initial volume list:\n\n$e\n";
1817 my @copies = grep { $_->holdable } @$cps;
1819 for (my $i = 0; $i < @$cps; $i++) {
1820 next unless $$cps[$i];
1822 my $cn = $cache{cns}{$copies[$i]->call_number};
1823 my $rec = $cache{titles}{$cn->record};
1824 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1825 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1826 $copies[$i] = undef if (
1828 !$self->{user_filter}->request(
1829 'open-ils.circ.permit_hold',
1830 $hold->to_fieldmapper, do {
1831 my $cp_fm = $copies[$i]->to_fieldmapper;
1832 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1833 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1834 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1837 { title => $rec->to_fieldmapper,
1838 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1839 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1842 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1845 @copies = grep { $_ } @copies;
1847 my $count = @copies;
1849 return unless ($count);
1851 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1854 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1855 for my $c (@copies) {
1856 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1858 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1864 sub choose_nearest_copy {
1866 my $prox_list = shift;
1868 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1869 next unless (ref $$prox_list[$p]);
1871 my @capturable = @{ $$prox_list[$p] };
1872 next unless (@capturable);
1874 my $rand = int(rand(scalar(@capturable)));
1876 while (my ($c) = splice(@capturable, $rand, 1)) {
1877 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
1878 { title => $c->call_number->record->to_fieldmapper,
1879 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1880 patron => $hold->usr->to_fieldmapper,
1881 copy => $c->to_fieldmapper,
1882 requestor => $hold->requestor->to_fieldmapper,
1883 request_lib => $hold->request_lib->to_fieldmapper,
1884 pickup_lib => $hold->pickup_lib->id,
1890 last unless(@capturable);
1891 $rand = int(rand(scalar(@capturable)));
1896 sub create_prox_list {
1901 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1904 for my $cp (@$copies) {
1905 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1906 next unless (defined($prox));
1908 my $copy_circ_lib = ''.$cp->circ_lib;
1909 # Fetch the weighting value for hold targeting, defaulting to 1
1910 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
1911 'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
1913 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
1914 $self->{target_weight}{$copy_circ_lib} ||= 1;
1916 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1917 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
1918 push @{$prox_list[$prox]}, $cp;
1924 sub volume_hold_capture {
1929 if (!defined($vols)) {
1931 $vols = [ asset::call_number->search( id => $hold->target ) ];
1932 $cache{cns}{$_->id} = $_ for (@$vols);
1933 } catch Error with {
1935 die "Could not retrieve initial volume list:\n\n$e\n";
1939 my @v_ids = map { $_->id } @$vols;
1943 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1945 } catch Error with {
1947 warn "Could not retrieve copy list:\n\n$e\n";
1950 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1953 sub title_hold_capture {
1958 if (!defined($titles)) {
1960 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1961 $cache{titles}{$_->id} = $_ for (@$titles);
1962 } catch Error with {
1964 die "Could not retrieve initial title list:\n\n$e\n";
1968 my @t_ids = map { $_->id } @$titles;
1971 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1973 } catch Error with {
1975 warn "Could not retrieve volume list:\n\n$e\n";
1978 $cache{cns}{$_->id} = $_ for (@$cn_list);
1980 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1983 sub metarecord_hold_capture {
1989 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1991 } catch Error with {
1993 die "Could not retrieve initial title list:\n\n$e\n";
1997 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1999 $titles = [ biblio::record_entry->search( id => \@recs ) ];
2001 } catch Error with {
2003 die "Could not retrieve format-pruned title list:\n\n$e\n";
2007 $cache{titles}{$_->id} = $_ for (@$titles);
2008 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);