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',
98 my $upper_interval = shift || '1 millennium';
101 my $c_t = action::circulation->table;
106 WHERE stop_fines IS NULL
107 AND due_date < ( CURRENT_TIMESTAMP - grace_period )
108 AND fine_interval < ?::INTERVAL
111 my $sth = action::circulation->db_Main->prepare_cached($sql);
112 $sth->execute($upper_interval);
114 my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
116 $c_t = booking::reservation->table;
120 WHERE return_time IS NULL
121 AND end_time < ( CURRENT_TIMESTAMP )
122 AND fine_interval IS NOT NULL
123 AND cancel_time IS NULL
126 $sth = action::circulation->db_Main->prepare_cached($sql);
129 push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
134 sub complete_reshelving {
139 local $OpenILS::Application::Storage::WRITE = 1;
141 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
142 unless (interval_to_seconds( $window ));
144 my $setting = actor::org_unit_setting->table;
145 my $circ = action::circulation->table;
146 my $cp = asset::copy->table;
147 my $atc = action::transit_copy->table;
154 FROM (SELECT cp.id, MAX(circ.checkin_time), MAX(trans.dest_recv_time)
156 JOIN $circ circ ON (circ.target_copy = cp.id)
157 LEFT JOIN $atc trans ON (trans.target_copy = cp.id)
158 LEFT JOIN $setting setting
159 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
160 WHERE circ.checkin_time IS NOT NULL
164 ( ( MAX(circ.checkin_time) > MAX(trans.dest_recv_time) or MAX(trans.dest_recv_time) IS NULL )
165 AND MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
167 ( MAX(trans.dest_recv_time) > MAX(circ.checkin_time)
168 AND MAX(trans.dest_recv_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
174 LEFT JOIN $setting setting
175 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
176 LEFT JOIN $circ circ ON (circ.target_copy = cp.id)
179 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
182 my $sth = action::circulation->db_Main->prepare_cached($sql);
183 $sth->execute($window, $window, $window);
188 __PACKAGE__->register_method(
189 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
192 method => 'complete_reshelving',
195 sub mark_longoverdue {
200 local $OpenILS::Application::Storage::WRITE = 1;
202 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
203 unless (interval_to_seconds( $window ));
205 my $setting = actor::org_unit_setting->table;
206 my $circ = action::circulation->table;
210 SET stop_fines = 'LONGOVERDUE',
211 stop_fines_time = now()
215 LEFT JOIN $setting setting
216 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
217 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
218 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
222 my $sth = action::circulation->db_Main->prepare_cached($sql);
223 $sth->execute($window);
228 __PACKAGE__->register_method(
229 api_name => 'open-ils.storage.action.circulation.long_overdue',
232 method => 'mark_longoverdue',
235 sub auto_thaw_frozen_holds {
239 local $OpenILS::Application::Storage::WRITE = 1;
241 my $holds = action::hold_request->table;
243 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
245 my $sth = action::hold_request->db_Main->prepare_cached($sql);
251 __PACKAGE__->register_method(
252 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
256 method => 'auto_thaw_frozen_holds',
263 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
265 $client->respond( $idlist ? $_ : $_->to_fieldmapper ) for ( overdue_circs('', $idlist) );
270 __PACKAGE__->register_method(
271 api_name => 'open-ils.storage.action.circulation.overdue',
274 method => 'grab_overdue',
276 Return list of overdue circulations and reservations to be used for fine generation.
277 Despite the name, this is not a generic method for retrieving all overdue loans,
278 as it excludes loans that have already hit the maximum fine limit.
281 __PACKAGE__->register_method(
282 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
285 method => 'grab_overdue',
293 my $limit = int(shift()) || 10;
294 my $age = shift() || '0 seconds';
297 local $OpenILS::Application::Storage::WRITE = 1;
299 my $holdsort = isTrue($fifo) ?
300 "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 " :
301 "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 ";
303 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
305 FROM action.hold_request h
306 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
307 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
308 JOIN actor.usr au ON (au.id = h.usr)
309 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
310 WHERE hm.target_copy = ?
311 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
312 AND h.capture_time IS NULL
313 AND h.cancel_time IS NULL
314 AND (h.expire_time IS NULL OR h.expire_time > NOW())
315 AND h.frozen IS FALSE
320 $client->respond( $_ ) for ( @$ids );
323 __PACKAGE__->register_method(
324 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
327 method => 'nearest_hold',
330 sub targetable_holds {
333 my $check_expire = shift;
335 $check_expire ||= '12h';
337 local $OpenILS::Application::Storage::WRITE = 1;
339 # json_query can *almost* represent this query, but can't
340 # handle the CASE statement or the interval arithmetic
341 my $query = <<" SQL";
342 SELECT ahr.id, mmsm.metarecord
343 FROM action.hold_request ahr
344 JOIN reporter.hold_request_record USING (id)
345 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
346 WHERE capture_time IS NULL
347 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
348 AND fulfillment_time IS NULL
349 AND cancel_time IS NULL
351 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
353 my $sth = action::hold_request->db_Main->prepare_cached($query);
354 $sth->execute($check_expire);
356 $client->respond( $_ ) for ( $sth->fetchall_arrayref );
360 __PACKAGE__->register_method(
361 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
364 method => 'targetable_holds',
366 Returns ordered list of hold request and metarecord IDs
367 for all hold requests that are available for initial targeting
369 @param check interval
370 @return list of pairs of hold request and metarecord IDs
374 sub next_resp_group_id {
378 # XXX This is not replication safe!!!
380 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
381 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
385 __PACKAGE__->register_method(
386 api_name => 'open-ils.storage.action.survey_response.next_group_id',
388 method => 'next_resp_group_id',
391 sub patron_circ_summary {
396 return undef unless ($id);
397 my $c_table = action::circulation->table;
398 my $b_table = money::billing->table;
400 $log->debug("Retrieving patron summary for id $id", DEBUG);
402 my $select = <<" SQL";
403 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
405 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
407 AND c.xact_finish IS NULL
409 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
410 OR c.stop_fines IS NULL
414 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
416 __PACKAGE__->register_method(
417 api_name => 'open-ils.storage.action.circulation.patron_summary',
419 method => 'patron_circ_summary',
422 #XXX Fix stored proc calls
423 sub find_local_surveys {
428 return undef unless ($ou);
429 my $s_table = action::survey->table;
431 my $select = <<" SQL";
434 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
435 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
438 my $sth = action::survey->db_Main->prepare_cached($select);
441 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
445 __PACKAGE__->register_method(
446 api_name => 'open-ils.storage.action.survey.all',
449 method => 'find_local_surveys',
452 #XXX Fix stored proc calls
453 sub find_opac_surveys {
458 return undef unless ($ou);
459 my $s_table = action::survey->table;
461 my $select = <<" SQL";
464 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
465 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
469 my $sth = action::survey->db_Main->prepare_cached($select);
472 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
476 __PACKAGE__->register_method(
477 api_name => 'open-ils.storage.action.survey.opac',
480 method => 'find_opac_surveys',
487 my $limit = shift || 10;
488 my $offset = shift || 0;
490 return undef unless ($ou);
491 my $h_table = action::hold_request->table;
492 my $a_table = asset::copy->table;
493 my $ord_table = asset::copy_location_order->table;
495 my $idlist = 1 if ($self->api_name =~/id_list/o);
496 my $count = 1 if ($self->api_name =~/count$/o);
498 my $status_filter = '';
499 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
501 my $select = <<" SQL";
504 JOIN $a_table a ON (h.current_copy = a.id)
505 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
507 AND h.capture_time IS NULL
508 AND h.cancel_time IS NULL
509 AND (h.expire_time IS NULL OR h.expire_time > NOW())
511 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
520 JOIN $a_table a ON (h.current_copy = a.id)
522 AND h.capture_time IS NULL
523 AND h.cancel_time IS NULL
524 AND (h.expire_time IS NULL OR h.expire_time > NOW())
529 my $sth = action::survey->db_Main->prepare_cached($select);
533 $client->respond( $sth->fetchall_arrayref()->[0][0] );
535 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
537 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
542 __PACKAGE__->register_method(
543 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
547 "Returns a count of holds for a specific library's pull list.",
548 [ [org_unit => "The library's org id", "number"] ],
549 ['A count of holds for the stated library to pull ', 'number']
551 method => 'hold_pull_list',
553 __PACKAGE__->register_method(
554 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
558 "Returns a status filtered count of holds for a specific library's pull list.",
559 [ [org_unit => "The library's org id", "number"] ],
560 ['A status filtered count of holds for the stated library to pull ', 'number']
562 method => 'hold_pull_list',
564 __PACKAGE__->register_method(
565 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
569 "Returns the hold ids for a specific library's pull list.",
570 [ [org_unit => "The library's org id", "number"],
571 [limit => 'An optional page size, defaults to 10', 'number'],
572 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
574 ['A list of holds for the stated library to pull for', 'array']
576 method => 'hold_pull_list',
578 __PACKAGE__->register_method(
579 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
583 "Returns the holds for a specific library's pull list.",
584 [ [org_unit => "The library's org id", "number"],
585 [limit => 'An optional page size, defaults to 10', 'number'],
586 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
588 ['A list of holds for the stated library to pull for', 'array']
590 method => 'hold_pull_list',
592 __PACKAGE__->register_method(
593 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
597 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
598 [ [org_unit => "The library's org id", "number"],
599 [limit => 'An optional page size, defaults to 10', 'number'],
600 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
602 ['A list of holds for the stated library to pull for', 'array']
604 method => 'hold_pull_list',
606 __PACKAGE__->register_method(
607 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
611 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
612 [ [org_unit => "The library's org id", "number"],
613 [limit => 'An optional page size, defaults to 10', 'number'],
614 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
616 ['A list of holds for the stated library to pull for', 'array']
618 method => 'hold_pull_list',
621 sub find_optional_surveys {
626 return undef unless ($ou);
627 my $s_table = action::survey->table;
629 my $select = <<" SQL";
632 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
633 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
634 AND s.required IS FALSE;
637 my $sth = action::survey->db_Main->prepare_cached($select);
640 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
644 __PACKAGE__->register_method(
645 api_name => 'open-ils.storage.action.survey.optional',
648 method => 'find_optional_surveys',
651 sub find_required_surveys {
656 return undef unless ($ou);
657 my $s_table = action::survey->table;
659 my $select = <<" SQL";
662 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
663 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
664 AND s.required IS TRUE;
667 my $sth = action::survey->db_Main->prepare_cached($select);
670 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
674 __PACKAGE__->register_method(
675 api_name => 'open-ils.storage.action.survey.required',
678 method => 'find_required_surveys',
681 sub find_usr_summary_surveys {
686 return undef unless ($ou);
687 my $s_table = action::survey->table;
689 my $select = <<" SQL";
692 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
693 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
694 AND s.usr_summary IS TRUE;
697 my $sth = action::survey->db_Main->prepare_cached($select);
700 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
704 __PACKAGE__->register_method(
705 api_name => 'open-ils.storage.action.survey.usr_summary',
708 method => 'find_usr_summary_surveys',
711 sub seconds_to_interval_hash {
712 my $interval = shift;
713 my $limit = shift || 's';
714 $limit =~ s/^(.)/$1/o;
718 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
719 my ($year, $month, $week, $day, $hour, $minute, $second) =
720 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
722 if ($y = int($interval / (60 * 60 * 24 * 365))) {
724 $ym = $interval % (60 * 60 * 24 * 365);
728 return %output if ($limit eq 'y');
730 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
731 $output{$month} = $M;
732 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
736 return %output if ($limit eq 'M');
738 if ($w = int($Mm / 604800)) {
744 return %output if ($limit eq 'w');
746 if ($d = int($wm / 86400)) {
752 return %output if ($limit eq 'd');
754 if ($h = int($dm / 3600)) {
760 return %output if ($limit eq 'h');
762 if ($m = int($hm / 60)) {
763 $output{$minute} = $m;
768 return %output if ($limit eq 'm');
771 $output{$second} = $s;
773 $output{$second} = 0 unless (keys %output);
783 my $overbill = shift;
785 local $OpenILS::Application::Storage::WRITE = 1;
790 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
791 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
793 push @circs, overdue_circs();
796 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
798 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
802 $ctype =~ s/^.+::(\w+)$/$1/;
804 my $due_date_method = 'due_date';
805 my $target_copy_method = 'target_copy';
806 my $circ_lib_method = 'circ_lib';
807 my $recurring_fine_method = 'recurring_fine';
808 my $is_reservation = 0;
809 if ($ctype eq 'reservation') {
811 $due_date_method = 'end_time';
812 $target_copy_method = 'current_resource';
813 $circ_lib_method = 'pickup_lib';
814 $recurring_fine_method = 'fine_amount';
815 next unless ($c->fine_interval);
817 #TODO: reservation grace periods
818 my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
821 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
822 $log->debug("Cleaning up after previous transaction\n");
823 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
825 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
827 sprintf("Processing %s %d...",
828 ($is_reservation ? "reservation" : "circ"), $c->id
833 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
835 my $due = $due_dt->epoch;
838 my $fine_interval = $c->fine_interval;
839 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
840 $fine_interval = interval_to_seconds( $fine_interval );
842 if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
843 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
844 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
848 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
850 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
851 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
854 $due -= ($due % $fine_interval) + $tz_offset_s;
855 $now -= ($now % $fine_interval) + $tz_offset_s;
859 "ARG! Overdue $ctype ".$c->id.
860 " for item ".$c->$target_copy_method.
861 " (user ".$c->usr.").\n".
862 "\tItem was due on or before: ".localtime($due)."\n");
864 my @fines = money::billing->search_where(
867 billing_ts => { '>' => $c->$due_date_method } },
868 { order_by => 'billing_ts DESC'}
872 my $fine = $fines[$f_idx] if (@fines);
874 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
877 my $current_fine_total = 0;
878 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
882 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
883 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
885 $log->info( "Potential first billing for circ ".$c->id );
889 if (my $h = $hoo{$c->$circ_lib_method}) {
891 $log->info( "Circ lib has an hours-of-operation entry" );
892 # find the day after the due date...
893 $due_dt = $due_dt->add( days => 1 );
895 # get the day of the week for that day...
896 my $dow = $due_dt->day_of_week_0;
897 my $dow_open = "dow_${dow}_open";
898 my $dow_close = "dow_${dow}_close";
901 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
902 # if the circ lib is closed, add a day to the grace period...
904 $grace_period+=86400;
905 $log->info( "Grace period for circ ".$c->id." extended to $grace_period [" . seconds_to_interval( $grace_period ) . "]" );
906 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
908 $due_dt = $due_dt->add( days => 1 );
909 $dow = $due_dt->day_of_week_0;
910 $dow_open = "dow_${dow}_open";
911 $dow_close = "dow_${dow}_close";
915 # and check for up to a week
916 last if ($count > 6);
922 next if ($last_fine > $now);
923 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
925 # Generate fines for the interval we are currently inside, when the fine interval is some multiple of 1d
926 $pending_fine_count++ if ($fine_interval && ($fine_interval % 86400 == 0));
928 if ( $last_fine == $due # we have no fines yet
929 && $grace_period # and we have a grace period
930 && $now < $due + $grace_period # and some date math says were are within the grace period
932 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
933 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
937 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
938 next unless ($pending_fine_count);
940 my $recurring_fine = int($c->$recurring_fine_method * 100);
941 my $max_fine = int($c->max_fine * 100);
943 my ($latest_billing_ts, $latest_amount) = ('',0);
944 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
946 if ($current_fine_total >= $max_fine) {
947 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
949 "\tMaximum fine level of ".$c->max_fine.
950 " reached for this $ctype.\n".
951 "\tNo more fines will be generated.\n" );
955 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
956 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
957 my $current_bill_count = $bill;
958 while ( $current_bill_count ) {
959 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
960 $current_bill_count--;
963 my $dow = $billing_ts->day_of_week_0();
964 my $dow_open = "dow_${dow}_open";
965 my $dow_close = "dow_${dow}_close";
967 if (my $h = $hoo{$c->$circ_lib_method}) {
968 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
971 my $timestamptz = $billing_ts->strftime('%FT%T%z');
972 my @cl = actor::org_unit::closed_date->search_where(
973 { close_start => { '<=' => $timestamptz },
974 close_end => { '>=' => $timestamptz },
975 org_unit => $c->$circ_lib_method }
979 $current_fine_total += $recurring_fine;
980 $latest_amount += $recurring_fine;
981 $latest_billing_ts = $timestamptz;
983 money::billing->create(
985 note => "System Generated Overdue Fine",
986 billing_type => "Overdue materials",
988 amount => sprintf('%0.2f', $recurring_fine/100),
989 billing_ts => $timestamptz,
995 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
996 if ($latest_billing_ts and $latest_amount);
998 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1002 # Caluclate penalties inline
1003 OpenILS::Utils::Penalty->calculate_penalties(
1004 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
1008 # Calculate penalties with an aysnc call to the penalty server. This approach
1009 # may lead to duplicate penalties since multiple penalty processes for a
1010 # given user may be running at the same time. Leave this here for reference
1011 # in case we later find that asyc calls are needed in some environments.
1013 'open-ils.penalty.patron_penalty.calculate',
1014 { patronid => ''.$c->usr,
1015 context_org => ''.$c->$circ_lib_method,
1022 } catch Error with {
1024 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
1025 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
1026 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1027 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1031 __PACKAGE__->register_method(
1032 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1035 method => 'generate_fines',
1040 sub new_hold_copy_targeter {
1043 my $check_expire = shift;
1044 my $one_hold = shift;
1046 local $OpenILS::Application::Storage::WRITE = 1;
1048 $self->{target_weight} = {};
1049 $self->{max_loops} = {};
1055 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1056 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
1057 } elsif ( $check_expire ) {
1059 # what's the retarget time threashold?
1061 $check_expire ||= '12h';
1062 $check_expire = interval_to_seconds( $check_expire );
1064 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1067 my $expire_threshold = sprintf(
1068 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1069 $year, $mon, $mday, $hour, $min, $sec
1072 # find all the holds holds needing retargeting
1073 $holds = [ action::hold_request->search_where(
1074 { capture_time => undef,
1075 fulfillment_time => undef,
1076 cancel_time => undef,
1078 prev_check_time => { '<=' => $expire_threshold },
1080 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
1082 # find all the holds holds needing first time targeting
1083 push @$holds, action::hold_request->search(
1084 capture_time => undef,
1085 fulfillment_time => undef,
1086 prev_check_time => undef,
1088 cancel_time => undef,
1089 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
1092 # find all the holds holds needing first time targeting ONLY
1093 $holds = [ action::hold_request->search(
1094 capture_time => undef,
1095 fulfillment_time => undef,
1096 prev_check_time => undef,
1097 cancel_time => undef,
1099 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
1101 } catch Error with {
1103 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1106 my @closed = actor::org_unit::closed_date->search_where(
1107 { close_start => { '<=', 'now' },
1108 close_end => { '>=', 'now' } }
1111 if ($check_expire) {
1113 # $check_expire, if it exists, was already converted to seconds
1114 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1118 my $next_check_time = sprintf(
1119 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1120 $year, $mon, $mday, $hour, $min, $sec
1124 my @closed_at_next = actor::org_unit::closed_date->search_where(
1125 { close_start => { '<=', $next_check_time },
1126 close_end => { '>=', $next_check_time } }
1130 for my $c_at_n (@closed_at_next) {
1131 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1132 push @new_closed, $c_at_n;
1135 @closed = @new_closed;
1139 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1141 for my $hold (@$holds) {
1143 #start a transaction if needed
1144 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1145 $log->debug("Cleaning up after previous transaction\n");
1146 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1148 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1149 $log->info("Processing hold ".$hold->id."...\n");
1151 #first, re-fetch the hold, to make sure it's not captured already
1152 $hold->remove_from_object_index();
1153 $hold = action::hold_request->retrieve( $hold->id );
1155 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1157 # remove old auto-targeting maps
1158 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1159 $_->delete for (@oldmaps);
1161 if ($hold->expire_time) {
1162 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1163 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1165 # cancel cause = un-targeted expiration
1166 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1167 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1169 # tell A/T the hold was cancelled
1170 my $fm_hold = $hold->to_fieldmapper;
1171 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1172 $ses->request('open-ils.trigger.event.autocreate',
1173 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1179 my $all_copies = [];
1181 # find filters for MR holds
1182 my ($types, $formats, $lang);
1183 if (defined($hold->holdable_formats)) {
1184 ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1187 # find all the potential copies
1188 if ($hold->hold_type eq 'M') {
1191 metabib::record_descriptor
1195 isTrue($_->deleted) ? () : ($_->id)
1196 } metabib::metarecord->retrieve($hold->target)->source_records
1198 ( $types ? (item_type => [split '', $types]) : () ),
1199 ( $formats ? (item_form => [split '', $formats]) : () ),
1200 ( $lang ? (item_lang => $lang) : () ),
1204 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1205 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1207 for my $cn ( @{ $rtree->call_numbers } ) {
1209 asset::copy->search_where(
1210 { id => [map {$_->id} @{ $cn->copies }],
1212 ) if ($cn && @{ $cn->copies });
1215 } elsif ($hold->hold_type eq 'T') {
1217 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1218 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1221 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1225 for my $cn ( @{ $rtree->call_numbers } ) {
1227 asset::copy->search_where(
1228 { id => [map {$_->id} @{ $cn->copies }],
1230 ) if ($cn && @{ $cn->copies });
1232 } elsif ($hold->hold_type eq 'V') {
1234 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1235 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1238 asset::copy->search_where(
1239 { id => [map {$_->id} @{ $vtree->copies }],
1241 ) if ($vtree && @{ $vtree->copies });
1243 } elsif ($hold->hold_type eq 'P') {
1244 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1246 asset::copy->search_where(
1247 { id => [map {$_->target_copy} @part_maps],
1252 } elsif ($hold->hold_type eq 'I') {
1254 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1255 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1258 asset::copy->search_where(
1259 { id => [map {$_->unit->id} @{ $itree->items }],
1261 ) if ($itree && @{ $itree->items });
1263 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1264 my $_cp = asset::copy->retrieve($hold->target);
1265 push @$all_copies, $_cp if $_cp;
1269 @$all_copies = grep { isTrue($_->status->holdable) &&
1270 isTrue($_->location->holdable) &&
1271 isTrue($_->holdable) &&
1272 !isTrue($_->deleted) &&
1273 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1) &&
1274 ($hold->hold_type ne 'P' ? $_->part_maps->count == 0 : 1)
1277 # let 'em know we're still working
1278 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1280 # if we have no copies ...
1281 if (!ref $all_copies || !@$all_copies) {
1282 $log->info("\tNo copies available for targeting at all!\n");
1283 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1285 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1286 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1290 my $copy_count = @$all_copies;
1292 # map the potentials, so that we can pick up checkins
1293 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1294 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1295 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1296 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1298 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1301 for my $c (@$all_copies) {
1303 next if ($c->id eq $hold->current_copy);
1305 # circ lib is closed
1306 next if ( 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) };
1497 $log->error("Processing of hold failed: $e");
1498 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1499 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1506 __PACKAGE__->register_method(
1507 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1509 method => 'new_hold_copy_targeter',
1512 sub process_recall {
1513 my ($actor, $log, $hold, $good_copies) = @_;
1515 # Bail early if we don't have required settings to avoid spurious requests
1516 my ($recall_threshold, $return_interval, $fine_rules);
1518 my $rv = $actor->request(
1519 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1523 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1526 $recall_threshold = $rv->{value};
1528 $rv = $actor->request(
1529 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1533 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1536 $return_interval = $rv->{value};
1538 $rv = $actor->request(
1539 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1543 $fine_rules = $rv->{value};
1546 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1548 # We want checked out copies (status = 1) at the hold pickup lib
1549 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1551 my @copy_ids = map { $_->id } @$all_copies;
1553 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1555 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1557 # Iterate over the checked-out copies to find a copy with a
1558 # loan period longer than the recall threshold:
1559 my $circs = [ action::circulation->search_where(
1560 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1561 { order_by => 'due_date ASC' }
1564 # If we have a candidate copy, then:
1565 if (scalar(@$circs)) {
1566 my $circ = $circs->[0];
1567 $log->info("Recalling circ ID : " . $circ->id);
1569 # Give the user a new due date of either a full recall threshold,
1570 # or the return interval, whichever is further in the future
1571 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1572 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1573 $return_date = $threshold_date;
1576 my $update_fields = {
1577 due_date => $return_date,
1578 renewal_remaining => 0,
1581 # If the OU hasn't defined new fine rules for recalls, keep them
1584 $log->info("Apply recall fine rules: $fine_rules");
1585 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1586 $update_fields->{recurring_fine} = $rules->[0];
1587 $update_fields->{fine_interval} = $rules->[1];
1588 $update_fields->{max_fine} = $rules->[2];
1591 # Adjust circ for current user
1592 $circ->update($update_fields);
1594 # Create trigger event for notifying current user
1595 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1596 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1599 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1602 sub reservation_targeter {
1605 my $one_reservation = shift;
1607 local $OpenILS::Application::Storage::WRITE = 1;
1612 if ($one_reservation) {
1613 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1614 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1617 # find all the reservations needing targeting
1619 booking::reservation->search_where(
1620 { current_resource => undef,
1621 cancel_time => undef,
1622 start_time => { '>' => 'now' }
1624 { order_by => 'start_time' }
1628 } catch Error with {
1630 die "Could not retrieve reservation requests:\n\n$e\n";
1634 for my $bresv (@$reservations) {
1636 #start a transaction if needed
1637 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1638 $log->debug("Cleaning up after previous transaction\n");
1639 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1641 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1642 $log->info("Processing reservation ".$bresv->id."...\n");
1644 #first, re-fetch the hold, to make sure it's not captured already
1645 $bresv->remove_from_object_index();
1646 $bresv = booking::reservation->retrieve( $bresv->id );
1648 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1650 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1651 if (DateTime->compare($end_time, DateTime->now) < 0) {
1653 # cancel cause = un-targeted expiration
1654 $bresv->update( { cancel_time => 'now' } );
1655 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1657 # tell A/T the reservation was cancelled
1658 my $fm_bresv = $bresv->to_fieldmapper;
1659 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1660 $ses->request('open-ils.trigger.event.autocreate',
1661 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1666 my $possible_resources;
1668 # find all the potential resources
1669 if (!$bresv->target_resource) {
1670 my $filter = { type => $bresv->target_resource_type };
1671 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1673 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1675 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1676 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1677 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1679 $possible_resources = $bresv->target_resource;
1682 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1683 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1686 my @good_resources = ();
1688 for my $res (@$all_resources) {
1689 unless (isTrue($res->type->catalog_item)) {
1690 push @good_resources, $res;
1694 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1697 push @good_resources, $res;
1701 # At this point, if we're just targeting one specific
1702 # resource, just succeed. We don't care about its present
1704 if ($bresv->target_resource) {
1705 push @good_resources, $res;
1709 if ($copy->status->id == 0 || $copy->status->id == 7) {
1710 push @good_resources, $res;
1714 if ($copy->status->id == 1) {
1715 my $circs = [ action::circulation->search_where(
1716 {target_copy => $copy->id, checkin_time => undef },
1717 { order_by => 'id DESC' }
1721 my $due_date = $circs->[0]->due_date;
1722 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1723 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1724 if (DateTime->compare($start_time, $due_date) < 0) {
1725 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1729 push @good_resources, $res;
1735 push @good_resources, $res if (isTrue($copy->status->holdable));
1738 # let 'em know we're still working
1739 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1741 # if we have no copies ...
1742 if (!@good_resources) {
1743 $log->info("\tNo resources available for targeting at all!\n");
1744 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1747 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1751 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1757 $_->owner == $bresv->pickup_lib
1761 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1762 # $all_copies is now a list of copies not at the pickup library
1764 my $best = shift @good_resources;
1765 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1768 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1772 sort { $a->[0] <=> $b->[0] }
1774 [ actor::org_unit_proximity->search_where(
1775 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1781 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1783 $best = shift @$prox_list
1787 $bresv->update( { current_resource => ''.$best->id } );
1788 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1791 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1792 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1795 { reservation => $bresv->id,
1796 current_resource => ($best ? $best->id : undef) };
1801 $log->error("Processing of bresv failed: $e");
1802 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1803 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1810 __PACKAGE__->register_method(
1811 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1813 method => 'reservation_targeter',
1818 my %cache = (titles => {}, cns => {});
1820 sub copy_hold_capture {
1825 if (!defined($cps)) {
1827 $cps = [ asset::copy->search( id => $hold->target ) ];
1828 } catch Error with {
1830 die "Could not retrieve initial volume list:\n\n$e\n";
1834 my @copies = grep { $_->holdable } @$cps;
1836 for (my $i = 0; $i < @$cps; $i++) {
1837 next unless $$cps[$i];
1839 my $cn = $cache{cns}{$copies[$i]->call_number};
1840 my $rec = $cache{titles}{$cn->record};
1841 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1842 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1843 $copies[$i] = undef if (
1845 !$self->{user_filter}->request(
1846 'open-ils.circ.permit_hold',
1847 $hold->to_fieldmapper, do {
1848 my $cp_fm = $copies[$i]->to_fieldmapper;
1849 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1850 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1851 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1854 { title => $rec->to_fieldmapper,
1855 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1856 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1859 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1862 @copies = grep { $_ } @copies;
1864 my $count = @copies;
1866 return unless ($count);
1868 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1871 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1872 for my $c (@copies) {
1873 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1875 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1881 sub choose_nearest_copy {
1883 my $prox_list = shift;
1885 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1886 next unless (ref $$prox_list[$p]);
1888 my @capturable = @{ $$prox_list[$p] };
1889 next unless (@capturable);
1891 my $rand = int(rand(scalar(@capturable)));
1893 while (my ($c) = splice(@capturable, $rand, 1)) {
1894 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
1895 { title => $c->call_number->record->to_fieldmapper,
1896 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1897 patron => $hold->usr->to_fieldmapper,
1898 copy => $c->to_fieldmapper,
1899 requestor => $hold->requestor->to_fieldmapper,
1900 request_lib => $hold->request_lib->to_fieldmapper,
1901 pickup_lib => $hold->pickup_lib->id,
1907 last unless(@capturable);
1908 $rand = int(rand(scalar(@capturable)));
1913 sub create_prox_list {
1918 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1921 for my $cp (@$copies) {
1922 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1923 next unless (defined($prox));
1925 my $copy_circ_lib = ''.$cp->circ_lib;
1926 # Fetch the weighting value for hold targeting, defaulting to 1
1927 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
1928 'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
1930 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
1931 $self->{target_weight}{$copy_circ_lib} ||= 1;
1933 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1934 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
1935 push @{$prox_list[$prox]}, $cp;
1941 sub volume_hold_capture {
1946 if (!defined($vols)) {
1948 $vols = [ asset::call_number->search( id => $hold->target ) ];
1949 $cache{cns}{$_->id} = $_ for (@$vols);
1950 } catch Error with {
1952 die "Could not retrieve initial volume list:\n\n$e\n";
1956 my @v_ids = map { $_->id } @$vols;
1960 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1962 } catch Error with {
1964 warn "Could not retrieve copy list:\n\n$e\n";
1967 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1970 sub title_hold_capture {
1975 if (!defined($titles)) {
1977 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1978 $cache{titles}{$_->id} = $_ for (@$titles);
1979 } catch Error with {
1981 die "Could not retrieve initial title list:\n\n$e\n";
1985 my @t_ids = map { $_->id } @$titles;
1988 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1990 } catch Error with {
1992 warn "Could not retrieve volume list:\n\n$e\n";
1995 $cache{cns}{$_->id} = $_ for (@$cn_list);
1997 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
2000 sub metarecord_hold_capture {
2006 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
2008 } catch Error with {
2010 die "Could not retrieve initial title list:\n\n$e\n";
2014 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
2016 $titles = [ biblio::record_entry->search( id => \@recs ) ];
2018 } catch Error with {
2020 die "Could not retrieve format-pruned title list:\n\n$e\n";
2024 $cache{titles}{$_->id} = $_ for (@$titles);
2025 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);