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 : $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 ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
844 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
845 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
848 $due -= ($due % $fine_interval) + $tz_offset_s;
849 $now -= ($now % $fine_interval) + $tz_offset_s;
853 "ARG! Overdue $ctype ".$c->id.
854 " for item ".$c->$target_copy_method.
855 " (user ".$c->usr.").\n".
856 "\tItem was due on or before: ".localtime($due)."\n");
858 my @fines = money::billing->search_where(
861 billing_ts => { '>' => $c->$due_date_method } },
862 { order_by => 'billing_ts DESC'}
866 my $fine = $fines[$f_idx] if (@fines);
868 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
871 my $current_fine_total = 0;
872 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
876 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
877 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
879 $log->info( "Potential first billing for circ ".$c->id );
883 if (my $h = $hoo{$c->$circ_lib_method}) {
885 $log->info( "Circ lib has an hours-of-operation entry" );
886 # find the day after the due date...
887 $due_dt = $due_dt->add( days => 1 );
889 # get the day of the week for that day...
890 my $dow = $due_dt->day_of_week_0;
891 my $dow_open = "dow_${dow}_open";
892 my $dow_close = "dow_${dow}_close";
895 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
896 # if the circ lib is closed, add a day to the grace period...
898 $grace_period+=86400;
899 $log->info( "Grace period for circ ".$c->id." extended to $grace_period [" . seconds_to_interval( $grace_period ) . "]" );
900 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
902 $due_dt = $due_dt->add( days => 1 );
903 $dow = $due_dt->day_of_week_0;
904 $dow_open = "dow_${dow}_open";
905 $dow_close = "dow_${dow}_close";
909 # and check for up to a week
910 last if ($count > 6);
916 next if ($last_fine > $now);
917 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
919 # Generate fines for the interval we are currently inside, when the fine interval is some multiple of 1d
920 $pending_fine_count++ if ($fine_interval && ($fine_interval % 86400 == 0));
922 if ( $last_fine == $due # we have no fines yet
923 && $grace_period # and we have a grace period
924 && $now < $due + $grace_period # and some date math says were are within the grace period
926 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
927 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
931 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
932 next unless ($pending_fine_count);
934 my $recurring_fine = int($c->$recurring_fine_method * 100);
935 my $max_fine = int($c->max_fine * 100);
937 my ($latest_billing_ts, $latest_amount) = ('',0);
938 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
940 if ($current_fine_total >= $max_fine) {
941 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
943 "\tMaximum fine level of ".$c->max_fine.
944 " reached for this $ctype.\n".
945 "\tNo more fines will be generated.\n" );
949 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
950 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
951 my $current_bill_count = $bill;
952 while ( $current_bill_count ) {
953 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
954 $current_bill_count--;
957 my $dow = $billing_ts->day_of_week_0();
958 my $dow_open = "dow_${dow}_open";
959 my $dow_close = "dow_${dow}_close";
961 if (my $h = $hoo{$c->$circ_lib_method}) {
962 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
965 my $timestamptz = $billing_ts->strftime('%FT%T%z');
966 my @cl = actor::org_unit::closed_date->search_where(
967 { close_start => { '<=' => $timestamptz },
968 close_end => { '>=' => $timestamptz },
969 org_unit => $c->$circ_lib_method }
973 $current_fine_total += $recurring_fine;
974 $latest_amount += $recurring_fine;
975 $latest_billing_ts = $timestamptz;
977 money::billing->create(
979 note => "System Generated Overdue Fine",
980 billing_type => "Overdue materials",
982 amount => sprintf('%0.2f', $recurring_fine/100),
983 billing_ts => $timestamptz,
989 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
990 if ($latest_billing_ts and $latest_amount);
992 $self->method_lookup('open-ils.storage.transaction.commit')->run;
996 # Caluclate penalties inline
997 OpenILS::Utils::Penalty->calculate_penalties(
998 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
1002 # Calculate penalties with an aysnc call to the penalty server. This approach
1003 # may lead to duplicate penalties since multiple penalty processes for a
1004 # given user may be running at the same time. Leave this here for reference
1005 # in case we later find that asyc calls are needed in some environments.
1007 'open-ils.penalty.patron_penalty.calculate',
1008 { patronid => ''.$c->usr,
1009 context_org => ''.$c->$circ_lib_method,
1016 } catch Error with {
1018 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
1019 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
1020 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1021 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1025 __PACKAGE__->register_method(
1026 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1029 method => 'generate_fines',
1034 sub new_hold_copy_targeter {
1037 my $check_expire = shift;
1038 my $one_hold = shift;
1040 local $OpenILS::Application::Storage::WRITE = 1;
1042 $self->{target_weight} = {};
1043 $self->{max_loops} = {};
1049 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1050 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
1051 } elsif ( $check_expire ) {
1053 # what's the retarget time threashold?
1055 $check_expire ||= '12h';
1056 $check_expire = interval_to_seconds( $check_expire );
1058 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1061 my $expire_threshold = sprintf(
1062 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1063 $year, $mon, $mday, $hour, $min, $sec
1066 # find all the holds holds needing retargeting
1067 $holds = [ action::hold_request->search_where(
1068 { capture_time => undef,
1069 fulfillment_time => undef,
1070 cancel_time => undef,
1072 prev_check_time => { '<=' => $expire_threshold },
1074 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
1076 # find all the holds holds needing first time targeting
1077 push @$holds, action::hold_request->search(
1078 capture_time => undef,
1079 fulfillment_time => undef,
1080 prev_check_time => undef,
1082 cancel_time => undef,
1083 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
1086 # find all the holds holds needing first time targeting ONLY
1087 $holds = [ action::hold_request->search(
1088 capture_time => undef,
1089 fulfillment_time => undef,
1090 prev_check_time => undef,
1091 cancel_time => undef,
1093 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
1095 } catch Error with {
1097 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1100 my @closed = actor::org_unit::closed_date->search_where(
1101 { close_start => { '<=', 'now' },
1102 close_end => { '>=', 'now' } }
1105 if ($check_expire) {
1107 # $check_expire, if it exists, was already converted to seconds
1108 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
1112 my $next_check_time = sprintf(
1113 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1114 $year, $mon, $mday, $hour, $min, $sec
1118 my @closed_at_next = actor::org_unit::closed_date->search_where(
1119 { close_start => { '<=', $next_check_time },
1120 close_end => { '>=', $next_check_time } }
1124 for my $c_at_n (@closed_at_next) {
1125 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
1126 push @new_closed, $c_at_n;
1129 @closed = @new_closed;
1133 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1135 for my $hold (@$holds) {
1137 #start a transaction if needed
1138 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1139 $log->debug("Cleaning up after previous transaction\n");
1140 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1142 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1143 $log->info("Processing hold ".$hold->id."...\n");
1145 #first, re-fetch the hold, to make sure it's not captured already
1146 $hold->remove_from_object_index();
1147 $hold = action::hold_request->retrieve( $hold->id );
1149 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
1151 # remove old auto-targeting maps
1152 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1153 $_->delete for (@oldmaps);
1155 if ($hold->expire_time) {
1156 my $ex_time = $parser->parse_datetime( cleanse_ISO8601( $hold->expire_time ) );
1157 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
1159 # cancel cause = un-targeted expiration
1160 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1161 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1163 # tell A/T the hold was cancelled
1164 my $fm_hold = $hold->to_fieldmapper;
1165 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1166 $ses->request('open-ils.trigger.event.autocreate',
1167 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1173 my $all_copies = [];
1175 # find filters for MR holds
1176 my ($types, $formats, $lang);
1177 if (defined($hold->holdable_formats)) {
1178 ($types, $formats, $lang) = split '-', $hold->holdable_formats;
1181 # find all the potential copies
1182 if ($hold->hold_type eq 'M') {
1185 metabib::record_descriptor
1189 isTrue($_->deleted) ? () : ($_->id)
1190 } metabib::metarecord->retrieve($hold->target)->source_records
1192 ( $types ? (item_type => [split '', $types]) : () ),
1193 ( $formats ? (item_form => [split '', $formats]) : () ),
1194 ( $lang ? (item_lang => $lang) : () ),
1198 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1199 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1201 for my $cn ( @{ $rtree->call_numbers } ) {
1203 asset::copy->search_where(
1204 { id => [map {$_->id} @{ $cn->copies }],
1206 ) if ($cn && @{ $cn->copies });
1209 } elsif ($hold->hold_type eq 'T') {
1211 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1212 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1215 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1219 for my $cn ( @{ $rtree->call_numbers } ) {
1221 asset::copy->search_where(
1222 { id => [map {$_->id} @{ $cn->copies }],
1224 ) if ($cn && @{ $cn->copies });
1226 } elsif ($hold->hold_type eq 'V') {
1228 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1229 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1232 asset::copy->search_where(
1233 { id => [map {$_->id} @{ $vtree->copies }],
1235 ) if ($vtree && @{ $vtree->copies });
1237 } elsif ($hold->hold_type eq 'P') {
1238 my @part_maps = asset::copy_part_map->search_where( { part => $hold->target } );
1240 asset::copy->search_where(
1241 { id => [map {$_->target_copy} @part_maps],
1246 } elsif ($hold->hold_type eq 'I') {
1248 ->method_lookup( 'open-ils.storage.serial.issuance.ranged_tree')
1249 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1252 asset::copy->search_where(
1253 { id => [map {$_->unit->id} @{ $itree->items }],
1255 ) if ($itree && @{ $itree->items });
1257 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1258 my $_cp = asset::copy->retrieve($hold->target);
1259 push @$all_copies, $_cp if $_cp;
1263 @$all_copies = grep { isTrue($_->status->holdable) &&
1264 isTrue($_->location->holdable) &&
1265 isTrue($_->holdable) &&
1266 !isTrue($_->deleted) &&
1267 (isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1)
1270 # let 'em know we're still working
1271 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1273 # if we have no copies ...
1274 if (!ref $all_copies || !@$all_copies) {
1275 $log->info("\tNo copies available for targeting at all!\n");
1276 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1278 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1279 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1283 my $copy_count = @$all_copies;
1285 # map the potentials, so that we can pick up checkins
1286 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1287 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1288 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1289 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1291 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1294 for my $c (@$all_copies) {
1296 next if ($c->id eq $hold->current_copy);
1298 # circ lib is closed
1299 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1301 # target of another hold
1302 next if (action::hold_request
1304 { current_copy => $c->id,
1305 fulfillment_time => undef,
1306 cancel_time => undef,
1311 # we passed all three, keep it
1312 push @good_copies, $c if ($c);
1313 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1316 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1318 my $old_best = $hold->current_copy;
1319 $hold->update({ current_copy => undef }) if ($old_best);
1321 if (!scalar(@good_copies)) {
1322 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1323 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1324 # the old copy is still available
1325 $log->debug("\tPushing current_copy back onto the targeting list");
1326 push @good_copies, $old_best;
1328 # oops, old copy is not available
1329 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1330 $hold->update( { prev_check_time => 'today' } );
1331 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1332 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1337 my $pu_lib = ''.$hold->pickup_lib;
1343 ''.$_->circ_lib eq $pu_lib &&
1344 ( $_->status == 0 || $_->status == 7 )
1348 $all_copies = [grep { $_->status == 0 || $_->status == 7 } grep {''.$_->circ_lib ne $pu_lib } @good_copies];
1349 # $all_copies is now a list of copies not at the pickup library
1351 my $best = choose_nearest_copy($hold, $prox_list);
1352 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1355 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1357 $self->{max_loops}{$pu_lib} = $actor->request(
1358 'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1361 if (defined($self->{max_loops}{$pu_lib})) {
1362 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1364 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1365 my $circ_lib_list = [keys %circ_lib_map];
1367 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1369 # Grab the "biggest" loop for this hold so far
1370 my $current_loop = $cstore->request(
1371 'open-ils.cstore.json_query',
1373 select => { aufhmxl => ['max'] },
1375 where => { hold => $hold->id}
1379 $current_loop = $current_loop->{max} if ($current_loop);
1380 $current_loop ||= 1;
1382 my $exclude_list = $cstore->request(
1383 'open-ils.cstore.json_query.atomic',
1385 select => { aufhol => ['circ_lib'] },
1387 where => { hold => $hold->id}
1392 if ($exclude_list && @$exclude_list) {
1393 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1394 # check to see if we've used up every library in the potentials list
1395 for my $l ( @$circ_lib_list ) {
1397 for my $ex ( @$exclude_list ) {
1403 push(@keepers, $l) if ($keep);
1406 @keepers = @$circ_lib_list;
1409 $current_loop++ if (!@keepers);
1411 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1412 # We haven't exceeded max_loops yet
1414 for my $cp ( @$all_copies ) {
1415 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1418 $all_copies = [@keeper_copies];
1420 # We have, and should remove potentials and cancel the hold
1421 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1422 $_->delete for (@oldmaps);
1424 # cancel cause = un-targeted expiration
1425 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1426 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1428 # tell A/T the hold was cancelled
1429 my $fm_hold = $hold->to_fieldmapper;
1430 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1431 $ses->request('open-ils.trigger.event.autocreate',
1432 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1438 $prox_list = create_prox_list( $self, $pu_lib, $all_copies );
1440 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1442 $best = choose_nearest_copy($hold, $prox_list);
1445 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1447 # hold wasn't fulfilled, record the fact
1449 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1450 action::unfulfilled_hold_list->create(
1451 { hold => ''.$hold->id,
1452 current_copy => ''.$old_best->id,
1453 circ_lib => ''.$old_best->circ_lib,
1458 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1459 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1462 !action::hold_request
1464 { current_copy => $old_best->id,
1465 fulfillment_time => undef,
1466 cancel_time => undef,
1470 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1471 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1473 $hold->update( { prev_check_time => 'now' } );
1474 $log->info( "\tThere were no targetable copies for the hold" );
1475 process_recall($actor, $log, $hold, \@good_copies);
1478 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1479 $log->info("\tProcessing of hold ".$hold->id." complete.");
1482 { hold => $hold->id,
1483 old_target => ($old_best ? $old_best->id : undef),
1484 eligible_copies => $copy_count,
1485 target => ($best ? $best->id : undef) };
1490 $log->error("Processing of hold failed: $e");
1491 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1492 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1499 __PACKAGE__->register_method(
1500 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1502 method => 'new_hold_copy_targeter',
1505 sub process_recall {
1506 my ($actor, $log, $hold, $good_copies) = @_;
1508 # Bail early if we don't have required settings to avoid spurious requests
1509 my ($recall_threshold, $return_interval, $fine_rules);
1511 my $rv = $actor->request(
1512 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1516 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1519 $recall_threshold = $rv->{value};
1521 $rv = $actor->request(
1522 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1526 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1529 $return_interval = $rv->{value};
1531 $rv = $actor->request(
1532 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1536 $fine_rules = $rv->{value};
1539 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1541 # We want checked out copies (status = 1) at the hold pickup lib
1542 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1544 my @copy_ids = map { $_->id } @$all_copies;
1546 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1548 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1550 # Iterate over the checked-out copies to find a copy with a
1551 # loan period longer than the recall threshold:
1552 my $circs = [ action::circulation->search_where(
1553 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1554 { order_by => 'due_date ASC' }
1557 # If we have a candidate copy, then:
1558 if (scalar(@$circs)) {
1559 my $circ = $circs->[0];
1560 $log->info("Recalling circ ID : " . $circ->id);
1562 # Give the user a new due date of either a full recall threshold,
1563 # or the return interval, whichever is further in the future
1564 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1565 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1566 $return_date = $threshold_date;
1569 my $update_fields = {
1570 due_date => $return_date,
1571 renewal_remaining => 0,
1574 # If the OU hasn't defined new fine rules for recalls, keep them
1577 $log->info("Apply recall fine rules: $fine_rules");
1578 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1579 $update_fields->{recurring_fine} = $rules->[0];
1580 $update_fields->{fine_interval} = $rules->[1];
1581 $update_fields->{max_fine} = $rules->[2];
1584 # Adjust circ for current user
1585 $circ->update($update_fields);
1587 # Create trigger event for notifying current user
1588 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1589 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1592 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1595 sub reservation_targeter {
1598 my $one_reservation = shift;
1600 local $OpenILS::Application::Storage::WRITE = 1;
1605 if ($one_reservation) {
1606 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1607 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1610 # find all the reservations needing targeting
1612 booking::reservation->search_where(
1613 { current_resource => undef,
1614 cancel_time => undef,
1615 start_time => { '>' => 'now' }
1617 { order_by => 'start_time' }
1621 } catch Error with {
1623 die "Could not retrieve reservation requests:\n\n$e\n";
1627 for my $bresv (@$reservations) {
1629 #start a transaction if needed
1630 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1631 $log->debug("Cleaning up after previous transaction\n");
1632 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1634 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1635 $log->info("Processing reservation ".$bresv->id."...\n");
1637 #first, re-fetch the hold, to make sure it's not captured already
1638 $bresv->remove_from_object_index();
1639 $bresv = booking::reservation->retrieve( $bresv->id );
1641 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1643 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1644 if (DateTime->compare($end_time, DateTime->now) < 0) {
1646 # cancel cause = un-targeted expiration
1647 $bresv->update( { cancel_time => 'now' } );
1648 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1650 # tell A/T the reservation was cancelled
1651 my $fm_bresv = $bresv->to_fieldmapper;
1652 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1653 $ses->request('open-ils.trigger.event.autocreate',
1654 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1659 my $possible_resources;
1661 # find all the potential resources
1662 if (!$bresv->target_resource) {
1663 my $filter = { type => $bresv->target_resource_type };
1664 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1666 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1668 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1669 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1670 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1672 $possible_resources = $bresv->target_resource;
1675 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1676 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1679 my @good_resources = ();
1681 for my $res (@$all_resources) {
1682 unless (isTrue($res->type->catalog_item)) {
1683 push @good_resources, $res;
1687 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1690 push @good_resources, $res;
1694 # At this point, if we're just targeting one specific
1695 # resource, just succeed. We don't care about its present
1697 if ($bresv->target_resource) {
1698 push @good_resources, $res;
1702 if ($copy->status->id == 0 || $copy->status->id == 7) {
1703 push @good_resources, $res;
1707 if ($copy->status->id == 1) {
1708 my $circs = [ action::circulation->search_where(
1709 {target_copy => $copy->id, checkin_time => undef },
1710 { order_by => 'id DESC' }
1714 my $due_date = $circs->[0]->due_date;
1715 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1716 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1717 if (DateTime->compare($start_time, $due_date) < 0) {
1718 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1722 push @good_resources, $res;
1728 push @good_resources, $res if (isTrue($copy->status->holdable));
1731 # let 'em know we're still working
1732 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1734 # if we have no copies ...
1735 if (!@good_resources) {
1736 $log->info("\tNo resources available for targeting at all!\n");
1737 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1740 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1744 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1750 $_->owner == $bresv->pickup_lib
1754 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1755 # $all_copies is now a list of copies not at the pickup library
1757 my $best = shift @good_resources;
1758 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1761 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1765 sort { $a->[0] <=> $b->[0] }
1767 [ actor::org_unit_proximity->search_where(
1768 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1774 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1776 $best = shift @$prox_list
1780 $bresv->update( { current_resource => ''.$best->id } );
1781 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1784 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1785 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1788 { reservation => $bresv->id,
1789 current_resource => ($best ? $best->id : undef) };
1794 $log->error("Processing of bresv failed: $e");
1795 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1796 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1803 __PACKAGE__->register_method(
1804 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1806 method => 'reservation_targeter',
1811 my %cache = (titles => {}, cns => {});
1813 sub copy_hold_capture {
1818 if (!defined($cps)) {
1820 $cps = [ asset::copy->search( id => $hold->target ) ];
1821 } catch Error with {
1823 die "Could not retrieve initial volume list:\n\n$e\n";
1827 my @copies = grep { $_->holdable } @$cps;
1829 for (my $i = 0; $i < @$cps; $i++) {
1830 next unless $$cps[$i];
1832 my $cn = $cache{cns}{$copies[$i]->call_number};
1833 my $rec = $cache{titles}{$cn->record};
1834 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1835 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1836 $copies[$i] = undef if (
1838 !$self->{user_filter}->request(
1839 'open-ils.circ.permit_hold',
1840 $hold->to_fieldmapper, do {
1841 my $cp_fm = $copies[$i]->to_fieldmapper;
1842 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1843 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1844 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1847 { title => $rec->to_fieldmapper,
1848 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1849 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1852 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1855 @copies = grep { $_ } @copies;
1857 my $count = @copies;
1859 return unless ($count);
1861 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1864 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1865 for my $c (@copies) {
1866 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1868 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1874 sub choose_nearest_copy {
1876 my $prox_list = shift;
1878 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1879 next unless (ref $$prox_list[$p]);
1881 my @capturable = @{ $$prox_list[$p] };
1882 next unless (@capturable);
1884 my $rand = int(rand(scalar(@capturable)));
1886 while (my ($c) = splice(@capturable, $rand, 1)) {
1887 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
1888 { title => $c->call_number->record->to_fieldmapper,
1889 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1890 patron => $hold->usr->to_fieldmapper,
1891 copy => $c->to_fieldmapper,
1892 requestor => $hold->requestor->to_fieldmapper,
1893 request_lib => $hold->request_lib->to_fieldmapper,
1894 pickup_lib => $hold->pickup_lib->id,
1900 last unless(@capturable);
1901 $rand = int(rand(scalar(@capturable)));
1906 sub create_prox_list {
1911 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1914 for my $cp (@$copies) {
1915 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1916 next unless (defined($prox));
1918 my $copy_circ_lib = ''.$cp->circ_lib;
1919 # Fetch the weighting value for hold targeting, defaulting to 1
1920 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
1921 'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
1923 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
1924 $self->{target_weight}{$copy_circ_lib} ||= 1;
1926 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1927 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
1928 push @{$prox_list[$prox]}, $cp;
1934 sub volume_hold_capture {
1939 if (!defined($vols)) {
1941 $vols = [ asset::call_number->search( id => $hold->target ) ];
1942 $cache{cns}{$_->id} = $_ for (@$vols);
1943 } catch Error with {
1945 die "Could not retrieve initial volume list:\n\n$e\n";
1949 my @v_ids = map { $_->id } @$vols;
1953 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1955 } catch Error with {
1957 warn "Could not retrieve copy list:\n\n$e\n";
1960 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1963 sub title_hold_capture {
1968 if (!defined($titles)) {
1970 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1971 $cache{titles}{$_->id} = $_ for (@$titles);
1972 } catch Error with {
1974 die "Could not retrieve initial title list:\n\n$e\n";
1978 my @t_ids = map { $_->id } @$titles;
1981 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1983 } catch Error with {
1985 warn "Could not retrieve volume list:\n\n$e\n";
1988 $cache{cns}{$_->id} = $_ for (@$cn_list);
1990 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1993 sub metarecord_hold_capture {
1999 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
2001 } catch Error with {
2003 die "Could not retrieve initial title list:\n\n$e\n";
2007 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
2009 $titles = [ biblio::record_entry->search( id => \@recs ) ];
2011 } catch Error with {
2013 die "Could not retrieve format-pruned title list:\n\n$e\n";
2017 $cache{titles}{$_->id} = $_ for (@$titles);
2018 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);