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;
19 return 1 if ($v == 1);
20 return 1 if ($v =~ /^t/io);
21 return 1 if ($v =~ /^y/io);
25 my $parser = DateTime::Format::ISO8601->new;
26 my $log = 'OpenSRF::Utils::Logger';
28 sub open_noncat_circs {
33 my $a = action::non_cataloged_circulation->table;
34 my $c = config::non_cataloged_type->table;
39 JOIN $c c ON (a.item_type = c.id)
40 WHERE a.circ_time + c.circ_duration > current_timestamp
44 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
46 __PACKAGE__->register_method(
47 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
48 method => 'open_noncat_circs',
54 sub ou_hold_requests {
59 my $h_table = action::hold_request->table;
60 my $c_table = asset::copy->table;
61 my $o_table = actor::org_unit->table;
66 JOIN $c_table cp ON (cp.id = h.current_copy)
67 JOIN $o_table ou ON (ou.id = cp.circ_lib)
69 AND h.capture_time IS NULL
70 AND h.cancel_time IS NULL
71 AND (h.expire_time IS NULL OR h.expire_time > NOW())
72 ORDER BY h.request_time
75 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
78 $client->respond($_) for (
81 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
85 } @{ $sth->fetchall_arrayref }
89 __PACKAGE__->register_method(
90 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
94 method => 'ou_hold_requests',
99 my $upper_interval = shift || '1 millennium';
102 my $c_t = action::circulation->table;
107 WHERE stop_fines IS NULL
108 AND due_date < ( CURRENT_TIMESTAMP - grace_period )
109 AND fine_interval < ?::INTERVAL
112 my $sth = action::circulation->db_Main->prepare_cached($sql);
113 $sth->execute($upper_interval);
115 my @circs = map { $idlist ? $_->{id} : action::circulation->construct($_) } $sth->fetchall_hash;
117 $c_t = booking::reservation->table;
121 WHERE return_time IS NULL
122 AND end_time < ( CURRENT_TIMESTAMP )
123 AND fine_interval IS NOT NULL
124 AND cancel_time IS NULL
127 $sth = action::circulation->db_Main->prepare_cached($sql);
130 push @circs, map { $idlist ? $_->{id} : booking::reservation->construct($_) } $sth->fetchall_hash;
135 sub complete_reshelving {
140 local $OpenILS::Application::Storage::WRITE = 1;
142 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
143 unless (interval_to_seconds( $window ));
145 my $setting = actor::org_unit_setting->table;
146 my $circ = action::circulation->table;
147 my $cp = asset::copy->table;
148 my $atc = action::transit_copy->table;
155 FROM (SELECT cp.id, MAX(circ.checkin_time), MAX(trans.dest_recv_time)
157 JOIN $circ circ ON (circ.target_copy = cp.id)
158 LEFT JOIN $atc trans ON (trans.target_copy = cp.id)
159 LEFT JOIN $setting setting
160 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
161 WHERE circ.checkin_time IS NOT NULL
165 ( ( MAX(circ.checkin_time) > MAX(trans.dest_recv_time) or MAX(trans.dest_recv_time) IS NULL )
166 AND MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
168 ( MAX(trans.dest_recv_time) > MAX(circ.checkin_time)
169 AND MAX(trans.dest_recv_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL) )
175 LEFT JOIN $setting setting
176 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
177 LEFT JOIN $circ circ ON (circ.target_copy = cp.id)
180 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
183 my $sth = action::circulation->db_Main->prepare_cached($sql);
184 $sth->execute($window, $window, $window);
189 __PACKAGE__->register_method(
190 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
193 method => 'complete_reshelving',
196 sub mark_longoverdue {
201 local $OpenILS::Application::Storage::WRITE = 1;
203 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
204 unless (interval_to_seconds( $window ));
206 my $setting = actor::org_unit_setting->table;
207 my $circ = action::circulation->table;
211 SET stop_fines = 'LONGOVERDUE',
212 stop_fines_time = now()
216 LEFT JOIN $setting setting
217 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
218 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
219 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
223 my $sth = action::circulation->db_Main->prepare_cached($sql);
224 $sth->execute($window);
229 __PACKAGE__->register_method(
230 api_name => 'open-ils.storage.action.circulation.long_overdue',
233 method => 'mark_longoverdue',
236 sub auto_thaw_frozen_holds {
240 local $OpenILS::Application::Storage::WRITE = 1;
242 my $holds = action::hold_request->table;
244 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
246 my $sth = action::hold_request->db_Main->prepare_cached($sql);
252 __PACKAGE__->register_method(
253 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
257 method => 'auto_thaw_frozen_holds',
264 my $idlist = $self->api_name =~/id_list/o ? 1 : 0;
266 $client->respond( $idlist ? $_ : $_->to_fieldmapper ) for ( overdue_circs('', $idlist) );
271 __PACKAGE__->register_method(
272 api_name => 'open-ils.storage.action.circulation.overdue',
275 method => 'grab_overdue',
277 Return list of overdue circulations and reservations to be used for fine generation.
278 Despite the name, this is not a generic method for retrieving all overdue loans,
279 as it excludes loans that have already hit the maximum fine limit.
282 __PACKAGE__->register_method(
283 api_name => 'open-ils.storage.action.circulation.overdue.id_list',
286 method => 'grab_overdue',
294 my $limit = int(shift()) || 10;
295 my $age = shift() || '0 seconds';
298 local $OpenILS::Application::Storage::WRITE = 1;
300 my $holdsort = isTrue($fifo) ?
301 "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 " :
302 "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 ";
304 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
306 FROM action.hold_request h
307 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
308 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
309 JOIN actor.usr au ON (au.id = h.usr)
310 JOIN permission.grp_tree pgt ON (au.profile = pgt.id)
311 WHERE hm.target_copy = ?
312 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
313 AND h.capture_time IS NULL
314 AND h.cancel_time IS NULL
315 AND (h.expire_time IS NULL OR h.expire_time > NOW())
316 AND h.frozen IS FALSE
321 $client->respond( $_ ) for ( @$ids );
324 __PACKAGE__->register_method(
325 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
328 method => 'nearest_hold',
331 sub targetable_holds {
334 my $check_expire = shift;
336 $check_expire ||= '12h';
338 local $OpenILS::Application::Storage::WRITE = 1;
340 # json_query can *almost* represent this query, but can't
341 # handle the CASE statement or the interval arithmetic
342 my $query = <<" SQL";
343 SELECT ahr.id, mmsm.metarecord
344 FROM action.hold_request ahr
345 JOIN reporter.hold_request_record USING (id)
346 JOIN metabib.metarecord_source_map mmsm ON (bib_record = source)
347 WHERE capture_time IS NULL
348 AND (prev_check_time IS NULL or prev_check_time < (NOW() - ?::interval))
349 AND fulfillment_time IS NULL
350 AND cancel_time IS NULL
352 ORDER BY CASE WHEN ahr.hold_type = 'F' THEN 0 ELSE 1 END, selection_depth DESC, request_time;
354 my $sth = action::hold_request->db_Main->prepare_cached($query);
355 $sth->execute($check_expire);
357 $client->respond( $_ ) for ( $sth->fetchall_arrayref );
361 __PACKAGE__->register_method(
362 api_name => 'open-ils.storage.action.hold_request.targetable_holds.id_list',
365 method => 'targetable_holds',
367 Returns ordered list of hold request and metarecord IDs
368 for all hold requests that are available for initial targeting
370 @param check interval
371 @return list of pairs of hold request and metarecord IDs
375 sub next_resp_group_id {
379 # XXX This is not replication safe!!!
381 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
382 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
386 __PACKAGE__->register_method(
387 api_name => 'open-ils.storage.action.survey_response.next_group_id',
389 method => 'next_resp_group_id',
392 sub patron_circ_summary {
397 return undef unless ($id);
398 my $c_table = action::circulation->table;
399 my $b_table = money::billing->table;
401 $log->debug("Retrieving patron summary for id $id", DEBUG);
403 my $select = <<" SQL";
404 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
406 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
408 AND c.xact_finish IS NULL
410 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
411 OR c.stop_fines IS NULL
415 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
417 __PACKAGE__->register_method(
418 api_name => 'open-ils.storage.action.circulation.patron_summary',
420 method => 'patron_circ_summary',
423 #XXX Fix stored proc calls
424 sub find_local_surveys {
429 return undef unless ($ou);
430 my $s_table = action::survey->table;
432 my $select = <<" SQL";
435 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
436 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
439 my $sth = action::survey->db_Main->prepare_cached($select);
442 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
446 __PACKAGE__->register_method(
447 api_name => 'open-ils.storage.action.survey.all',
450 method => 'find_local_surveys',
453 #XXX Fix stored proc calls
454 sub find_opac_surveys {
459 return undef unless ($ou);
460 my $s_table = action::survey->table;
462 my $select = <<" SQL";
465 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
466 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
470 my $sth = action::survey->db_Main->prepare_cached($select);
473 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
477 __PACKAGE__->register_method(
478 api_name => 'open-ils.storage.action.survey.opac',
481 method => 'find_opac_surveys',
488 my $limit = shift || 10;
489 my $offset = shift || 0;
491 return undef unless ($ou);
492 my $h_table = action::hold_request->table;
493 my $a_table = asset::copy->table;
494 my $ord_table = asset::copy_location_order->table;
496 my $idlist = 1 if ($self->api_name =~/id_list/o);
497 my $count = 1 if ($self->api_name =~/count$/o);
499 my $status_filter = '';
500 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
502 my $select = <<" SQL";
505 JOIN $a_table a ON (h.current_copy = a.id)
506 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
508 AND h.capture_time IS NULL
509 AND h.cancel_time IS NULL
510 AND (h.expire_time IS NULL OR h.expire_time > NOW())
512 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
521 JOIN $a_table a ON (h.current_copy = a.id)
523 AND h.capture_time IS NULL
524 AND h.cancel_time IS NULL
525 AND (h.expire_time IS NULL OR h.expire_time > NOW())
530 my $sth = action::survey->db_Main->prepare_cached($select);
534 $client->respond( $sth->fetchall_arrayref()->[0][0] );
536 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
538 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
543 __PACKAGE__->register_method(
544 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
548 "Returns a count of holds for a specific library's pull list.",
549 [ [org_unit => "The library's org id", "number"] ],
550 ['A count of holds for the stated library to pull ', 'number']
552 method => 'hold_pull_list',
554 __PACKAGE__->register_method(
555 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
559 "Returns a status filtered count of holds for a specific library's pull list.",
560 [ [org_unit => "The library's org id", "number"] ],
561 ['A status filtered count of holds for the stated library to pull ', 'number']
563 method => 'hold_pull_list',
565 __PACKAGE__->register_method(
566 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
570 "Returns the hold ids for a specific library's pull list.",
571 [ [org_unit => "The library's org id", "number"],
572 [limit => 'An optional page size, defaults to 10', 'number'],
573 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
575 ['A list of holds for the stated library to pull for', 'array']
577 method => 'hold_pull_list',
579 __PACKAGE__->register_method(
580 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
584 "Returns the holds for a specific library's pull list.",
585 [ [org_unit => "The library's org id", "number"],
586 [limit => 'An optional page size, defaults to 10', 'number'],
587 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
589 ['A list of holds for the stated library to pull for', 'array']
591 method => 'hold_pull_list',
593 __PACKAGE__->register_method(
594 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
598 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
599 [ [org_unit => "The library's org id", "number"],
600 [limit => 'An optional page size, defaults to 10', 'number'],
601 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
603 ['A list of holds for the stated library to pull for', 'array']
605 method => 'hold_pull_list',
607 __PACKAGE__->register_method(
608 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
612 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
613 [ [org_unit => "The library's org id", "number"],
614 [limit => 'An optional page size, defaults to 10', 'number'],
615 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
617 ['A list of holds for the stated library to pull for', 'array']
619 method => 'hold_pull_list',
622 sub find_optional_surveys {
627 return undef unless ($ou);
628 my $s_table = action::survey->table;
630 my $select = <<" SQL";
633 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
634 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
635 AND s.required IS FALSE;
638 my $sth = action::survey->db_Main->prepare_cached($select);
641 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
645 __PACKAGE__->register_method(
646 api_name => 'open-ils.storage.action.survey.optional',
649 method => 'find_optional_surveys',
652 sub find_required_surveys {
657 return undef unless ($ou);
658 my $s_table = action::survey->table;
660 my $select = <<" SQL";
663 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
664 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
665 AND s.required IS TRUE;
668 my $sth = action::survey->db_Main->prepare_cached($select);
671 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
675 __PACKAGE__->register_method(
676 api_name => 'open-ils.storage.action.survey.required',
679 method => 'find_required_surveys',
682 sub find_usr_summary_surveys {
687 return undef unless ($ou);
688 my $s_table = action::survey->table;
690 my $select = <<" SQL";
693 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
694 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
695 AND s.usr_summary IS TRUE;
698 my $sth = action::survey->db_Main->prepare_cached($select);
701 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
705 __PACKAGE__->register_method(
706 api_name => 'open-ils.storage.action.survey.usr_summary',
709 method => 'find_usr_summary_surveys',
712 sub seconds_to_interval_hash {
713 my $interval = shift;
714 my $limit = shift || 's';
715 $limit =~ s/^(.)/$1/o;
719 my ($y,$ym,$M,$Mm,$w,$wm,$d,$dm,$h,$hm,$m,$mm,$s);
720 my ($year, $month, $week, $day, $hour, $minute, $second) =
721 ('years','months','weeks','days', 'hours', 'minutes', 'seconds');
723 if ($y = int($interval / (60 * 60 * 24 * 365))) {
725 $ym = $interval % (60 * 60 * 24 * 365);
729 return %output if ($limit eq 'y');
731 if ($M = int($ym / ((60 * 60 * 24 * 365)/12))) {
732 $output{$month} = $M;
733 $Mm = $ym % ((60 * 60 * 24 * 365)/12);
737 return %output if ($limit eq 'M');
739 if ($w = int($Mm / 604800)) {
745 return %output if ($limit eq 'w');
747 if ($d = int($wm / 86400)) {
753 return %output if ($limit eq 'd');
755 if ($h = int($dm / 3600)) {
761 return %output if ($limit eq 'h');
763 if ($m = int($hm / 60)) {
764 $output{$minute} = $m;
769 return %output if ($limit eq 'm');
772 $output{$second} = $s;
774 $output{$second} = 0 unless (keys %output);
784 my $overbill = shift;
786 local $OpenILS::Application::Storage::WRITE = 1;
791 action::circulation->search_where( { id => $circ, stop_fines => undef } ),
792 booking::reservation->search_where( { id => $circ, return_time => undef, cancel_time => undef } );
794 push @circs, overdue_circs();
797 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
799 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
803 $ctype =~ s/^.+::(\w+)$/$1/;
805 my $due_date_method = 'due_date';
806 my $target_copy_method = 'target_copy';
807 my $circ_lib_method = 'circ_lib';
808 my $recurring_fine_method = 'recurring_fine';
809 my $is_reservation = 0;
810 if ($ctype eq 'reservation') {
812 $due_date_method = 'end_time';
813 $target_copy_method = 'current_resource';
814 $circ_lib_method = 'pickup_lib';
815 $recurring_fine_method = 'fine_amount';
816 next unless ($c->fine_interval);
818 #TODO: reservation grace periods
819 my $grace_period = ($is_reservation ? 0 : interval_to_seconds($c->grace_period));
822 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
823 $log->debug("Cleaning up after previous transaction\n");
824 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
826 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
828 sprintf("Processing %s %d...",
829 ($is_reservation ? "reservation" : "circ"), $c->id
834 my $due_dt = $parser->parse_datetime( cleanse_ISO8601( $c->$due_date_method ) );
836 my $due = $due_dt->epoch;
839 my $fine_interval = $c->fine_interval;
840 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
841 $fine_interval = interval_to_seconds( $fine_interval );
843 if ( $fine_interval == 0 || int($c->$recurring_fine_method * 100) == 0 || int($c->max_fine * 100) == 0 ) {
844 $client->respond( "Fine Generator skipping circ due to 0 fine interval, 0 fine rate, or 0 max fine.\n" );
845 $log->info( "Fine Generator skipping circ " . $c->id . " due to 0 fine interval, 0 fine rate, or 0 max fine." );
849 if ( $is_reservation and $fine_interval >= interval_to_seconds('1d') ) {
851 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
852 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
855 $due -= ($due % $fine_interval) + $tz_offset_s;
856 $now -= ($now % $fine_interval) + $tz_offset_s;
860 "ARG! Overdue $ctype ".$c->id.
861 " for item ".$c->$target_copy_method.
862 " (user ".$c->usr.").\n".
863 "\tItem was due on or before: ".localtime($due)."\n");
865 my @fines = money::billing->search_where(
868 billing_ts => { '>' => $c->$due_date_method } },
869 { order_by => 'billing_ts DESC'}
873 my $fine = $fines[$f_idx] if (@fines);
875 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
878 my $current_fine_total = 0;
879 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
883 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed format: ".cleanse_ISO8601( $fine->billing_ts ).")");
884 $last_fine = $parser->parse_datetime( cleanse_ISO8601( $fine->billing_ts ) )->epoch;
886 $log->info( "Potential first billing for circ ".$c->id );
890 if (my $h = $hoo{$c->$circ_lib_method}) {
892 $log->info( "Circ lib has an hours-of-operation entry" );
893 # find the day after the due date...
894 $due_dt = $due_dt->add( days => 1 );
896 # get the day of the week for that day...
897 my $dow = $due_dt->day_of_week_0;
898 my $dow_open = "dow_${dow}_open";
899 my $dow_close = "dow_${dow}_close";
902 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
903 # if the circ lib is closed, add a day to the grace period...
905 $grace_period+=86400;
906 $log->info( "Grace period for circ ".$c->id." extended to $grace_period [" . seconds_to_interval( $grace_period ) . "]" );
907 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
909 $due_dt = $due_dt->add( days => 1 );
910 $dow = $due_dt->day_of_week_0;
911 $dow_open = "dow_${dow}_open";
912 $dow_close = "dow_${dow}_close";
916 # and check for up to a week
917 last if ($count > 6);
923 next if ($last_fine > $now);
924 # Generate fines for each past interval, including the one we are inside
925 my $pending_fine_count = ceil( ($now - $last_fine) / $fine_interval );
927 if ( $last_fine == $due # we have no fines yet
928 && $grace_period # and we have a grace period
929 && $now < $due + $grace_period # and some date math says were are within the grace period
931 $client->respond( "Still inside grace period of: ". seconds_to_interval( $grace_period )."\n" );
932 $log->info( "Circ ".$c->id." is still inside grace period of: $grace_period [". seconds_to_interval( $grace_period ).']' );
936 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
937 next unless ($pending_fine_count);
939 my $recurring_fine = int($c->$recurring_fine_method * 100);
940 my $max_fine = int($c->max_fine * 100);
942 my ($latest_billing_ts, $latest_amount) = ('',0);
943 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
945 if ($current_fine_total >= $max_fine) {
946 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'}) if ($ctype eq 'circulation');
948 "\tMaximum fine level of ".$c->max_fine.
949 " reached for this $ctype.\n".
950 "\tNo more fines will be generated.\n" );
954 # XXX Use org time zone (or default to 'local') once we have the ou setting built for that
955 my $billing_ts = DateTime->from_epoch( epoch => $last_fine, time_zone => 'local' );
956 my $current_bill_count = $bill;
957 while ( $current_bill_count ) {
958 $billing_ts->add( seconds_to_interval_hash( $fine_interval ) );
959 $current_bill_count--;
962 my $dow = $billing_ts->day_of_week_0();
963 my $dow_open = "dow_${dow}_open";
964 my $dow_close = "dow_${dow}_close";
966 if (my $h = $hoo{$c->$circ_lib_method}) {
967 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
970 my $timestamptz = $billing_ts->strftime('%FT%T%z');
971 my @cl = actor::org_unit::closed_date->search_where(
972 { close_start => { '<=' => $timestamptz },
973 close_end => { '>=' => $timestamptz },
974 org_unit => $c->$circ_lib_method }
978 $current_fine_total += $recurring_fine;
979 $latest_amount += $recurring_fine;
980 $latest_billing_ts = $timestamptz;
982 money::billing->create(
984 note => "System Generated Overdue Fine",
985 billing_type => "Overdue materials",
987 amount => sprintf('%0.2f', $recurring_fine/100),
988 billing_ts => $timestamptz,
994 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
995 if ($latest_billing_ts and $latest_amount);
997 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1001 # Caluclate penalties inline
1002 OpenILS::Utils::Penalty->calculate_penalties(
1003 undef, $c->usr->to_fieldmapper->id.'', $c->$circ_lib_method->to_fieldmapper->id.'');
1007 # Calculate penalties with an aysnc call to the penalty server. This approach
1008 # may lead to duplicate penalties since multiple penalty processes for a
1009 # given user may be running at the same time. Leave this here for reference
1010 # in case we later find that asyc calls are needed in some environments.
1012 'open-ils.penalty.patron_penalty.calculate',
1013 { patronid => ''.$c->usr,
1014 context_org => ''.$c->$circ_lib_method,
1021 } catch Error with {
1023 $client->respond( "Error processing overdue $ctype [".$c->id."]:\n\n$e\n" );
1024 $log->error("Error processing overdue $ctype [".$c->id."]:\n$e\n");
1025 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1026 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1030 __PACKAGE__->register_method(
1031 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
1034 method => 'generate_fines',
1039 sub new_hold_copy_targeter {
1042 my $check_expire = shift;
1043 my $one_hold = shift;
1044 my $find_copy = 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;
1291 my $found_copy = undef;
1292 $found_copy = 1 if($find_copy and grep $_ == $find_copy, @$all_copies);
1294 # map the potentials, so that we can pick up checkins
1295 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1296 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1297 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1298 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1300 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1303 for my $c (@$all_copies) {
1305 next if ($c->id eq $hold->current_copy);
1307 # circ lib is closed
1308 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1310 # target of another hold
1311 next if (action::hold_request
1313 { current_copy => $c->id,
1314 fulfillment_time => undef,
1315 cancel_time => undef,
1320 # we passed all three, keep it
1321 push @good_copies, $c if ($c);
1322 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1325 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1327 my $old_best = $hold->current_copy;
1328 $hold->update({ current_copy => undef }) if ($old_best);
1330 if (!scalar(@good_copies)) {
1331 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1332 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1333 # the old copy is still available
1334 $log->debug("\tPushing current_copy back onto the targeting list");
1335 push @good_copies, $old_best;
1337 # oops, old copy is not available
1338 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1339 $hold->update( { prev_check_time => 'today' } );
1340 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1341 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1346 my $pu_lib = ''.$hold->pickup_lib;
1352 ''.$_->circ_lib eq $pu_lib &&
1353 ( $_->status == 0 || $_->status == 7 )
1357 $all_copies = [grep { $_->status == 0 || $_->status == 7 } grep {''.$_->circ_lib ne $pu_lib } @good_copies];
1358 # $all_copies is now a list of copies not at the pickup library
1360 my $best = choose_nearest_copy($hold, $prox_list);
1361 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1364 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1366 $self->{max_loops}{$pu_lib} = $actor->request(
1367 'open-ils.actor.ou_setting.ancestor_default' => $pu_lib => 'circ.holds.max_org_unit_target_loops'
1370 if (defined($self->{max_loops}{$pu_lib})) {
1371 $self->{max_loops}{$pu_lib} = $self->{max_loops}{$pu_lib}{value};
1373 my %circ_lib_map = map { (''.$_->circ_lib => 1) } @$all_copies;
1374 my $circ_lib_list = [keys %circ_lib_map];
1376 my $cstore = OpenSRF::AppSession->create('open-ils.cstore');
1378 # Grab the "biggest" loop for this hold so far
1379 my $current_loop = $cstore->request(
1380 'open-ils.cstore.json_query',
1382 select => { aufhmxl => ['max'] },
1384 where => { hold => $hold->id}
1388 $current_loop = $current_loop->{max} if ($current_loop);
1389 $current_loop ||= 1;
1391 my $exclude_list = $cstore->request(
1392 'open-ils.cstore.json_query.atomic',
1394 select => { aufhol => ['circ_lib'] },
1396 where => { hold => $hold->id}
1401 if ($exclude_list && @$exclude_list) {
1402 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1403 # check to see if we've used up every library in the potentials list
1404 for my $l ( @$circ_lib_list ) {
1406 for my $ex ( @$exclude_list ) {
1412 push(@keepers, $l) if ($keep);
1415 @keepers = @$circ_lib_list;
1418 $current_loop++ if (!@keepers);
1420 if ($self->{max_loops}{$pu_lib} && $self->{max_loops}{$pu_lib} >= $current_loop) {
1421 # We haven't exceeded max_loops yet
1423 for my $cp ( @$all_copies ) {
1424 push(@keeper_copies, $cp) if ( !@keepers || grep { $_ eq ''.$cp->circ_lib } @keepers );
1427 $all_copies = [@keeper_copies];
1429 # We have, and should remove potentials and cancel the hold
1430 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1431 $_->delete for (@oldmaps);
1433 # cancel cause = un-targeted expiration
1434 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1435 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1437 # tell A/T the hold was cancelled
1438 my $fm_hold = $hold->to_fieldmapper;
1439 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1440 $ses->request('open-ils.trigger.event.autocreate',
1441 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1447 $prox_list = create_prox_list( $self, $pu_lib, $all_copies );
1449 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1451 $best = choose_nearest_copy($hold, $prox_list);
1454 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1456 # hold wasn't fulfilled, record the fact
1458 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1459 action::unfulfilled_hold_list->create(
1460 { hold => ''.$hold->id,
1461 current_copy => ''.$old_best->id,
1462 circ_lib => ''.$old_best->circ_lib,
1467 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1468 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1471 !action::hold_request
1473 { current_copy => $old_best->id,
1474 fulfillment_time => undef,
1475 cancel_time => undef,
1479 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1480 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1482 $hold->update( { prev_check_time => 'now' } );
1483 $log->info( "\tThere were no targetable copies for the hold" );
1484 process_recall($actor, $log, $hold, \@good_copies);
1487 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1488 $log->info("\tProcessing of hold ".$hold->id." complete.");
1491 { hold => $hold->id,
1492 old_target => ($old_best ? $old_best->id : undef),
1493 eligible_copies => $copy_count,
1494 target => ($best ? $best->id : undef),
1495 found_copy => $found_copy };
1500 $log->error("Processing of hold failed: $e");
1501 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1502 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1509 __PACKAGE__->register_method(
1510 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1512 method => 'new_hold_copy_targeter',
1515 sub process_recall {
1516 my ($actor, $log, $hold, $good_copies) = @_;
1518 # Bail early if we don't have required settings to avoid spurious requests
1519 my ($recall_threshold, $return_interval, $fine_rules);
1521 my $rv = $actor->request(
1522 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_threshold'
1526 $log->info("Recall threshold was not set; bailing out on hold ".$hold->id." processing.");
1529 $recall_threshold = $rv->{value};
1531 $rv = $actor->request(
1532 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_return_interval'
1536 $log->info("Recall return interval was not set; bailing out on hold ".$hold->id." processing.");
1539 $return_interval = $rv->{value};
1541 $rv = $actor->request(
1542 'open-ils.actor.ou_setting.ancestor_default', ''.$hold->pickup_lib, 'circ.holds.recall_fine_rules'
1546 $fine_rules = $rv->{value};
1549 $log->info("Recall threshold: $recall_threshold; return interval: $return_interval");
1551 # We want checked out copies (status = 1) at the hold pickup lib
1552 my $all_copies = [grep { $_->status == 1 } grep {''.$_->circ_lib eq ''.$hold->pickup_lib } @$good_copies];
1554 my @copy_ids = map { $_->id } @$all_copies;
1556 $log->info("Found " . scalar(@$all_copies) . " eligible checked-out copies for recall");
1558 my $return_date = DateTime->now(time_zone => 'local')->add(seconds => interval_to_seconds($return_interval))->iso8601();
1560 # Iterate over the checked-out copies to find a copy with a
1561 # loan period longer than the recall threshold:
1562 my $circs = [ action::circulation->search_where(
1563 { target_copy => \@copy_ids, checkin_time => undef, duration => { '>' => $recall_threshold } },
1564 { order_by => 'due_date ASC' }
1567 # If we have a candidate copy, then:
1568 if (scalar(@$circs)) {
1569 my $circ = $circs->[0];
1570 $log->info("Recalling circ ID : " . $circ->id);
1572 # Give the user a new due date of either a full recall threshold,
1573 # or the return interval, whichever is further in the future
1574 my $threshold_date = DateTime::Format::ISO8601->parse_datetime(cleanse_ISO8601($circ->xact_start))->add(seconds => interval_to_seconds($recall_threshold))->iso8601();
1575 if (DateTime->compare(DateTime::Format::ISO8601->parse_datetime($threshold_date), DateTime::Format::ISO8601->parse_datetime($return_date)) == 1) {
1576 $return_date = $threshold_date;
1579 my $update_fields = {
1580 due_date => $return_date,
1581 renewal_remaining => 0,
1584 # If the OU hasn't defined new fine rules for recalls, keep them
1587 $log->info("Apply recall fine rules: $fine_rules");
1588 my $rules = OpenSRF::Utils::JSON->JSON2perl($fine_rules);
1589 $update_fields->{recurring_fine} = $rules->[0];
1590 $update_fields->{fine_interval} = $rules->[1];
1591 $update_fields->{max_fine} = $rules->[2];
1594 # Adjust circ for current user
1595 $circ->update($update_fields);
1597 # Create trigger event for notifying current user
1598 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1599 $ses->request('open-ils.trigger.event.autocreate', 'circ.recall.target', $circ->to_fieldmapper(), $circ->circ_lib->id);
1602 $log->info("Processing of hold ".$hold->id." for recall is now complete.");
1605 sub reservation_targeter {
1608 my $one_reservation = shift;
1610 local $OpenILS::Application::Storage::WRITE = 1;
1615 if ($one_reservation) {
1616 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1617 $reservations = [ booking::reservation->search_where( { id => $one_reservation, capture_time => undef, cancel_time => undef } ) ];
1620 # find all the reservations needing targeting
1622 booking::reservation->search_where(
1623 { current_resource => undef,
1624 cancel_time => undef,
1625 start_time => { '>' => 'now' }
1627 { order_by => 'start_time' }
1631 } catch Error with {
1633 die "Could not retrieve reservation requests:\n\n$e\n";
1637 for my $bresv (@$reservations) {
1639 #start a transaction if needed
1640 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1641 $log->debug("Cleaning up after previous transaction\n");
1642 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1644 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1645 $log->info("Processing reservation ".$bresv->id."...\n");
1647 #first, re-fetch the hold, to make sure it's not captured already
1648 $bresv->remove_from_object_index();
1649 $bresv = booking::reservation->retrieve( $bresv->id );
1651 die "OK\n" if (!$bresv or $bresv->capture_time or $bresv->cancel_time);
1653 my $end_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->end_time ) );
1654 if (DateTime->compare($end_time, DateTime->now) < 0) {
1656 # cancel cause = un-targeted expiration
1657 $bresv->update( { cancel_time => 'now' } );
1658 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1660 # tell A/T the reservation was cancelled
1661 my $fm_bresv = $bresv->to_fieldmapper;
1662 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1663 $ses->request('open-ils.trigger.event.autocreate',
1664 'booking.reservation.cancel.expire_no_target', $fm_bresv, $fm_bresv->pickup_lib);
1669 my $possible_resources;
1671 # find all the potential resources
1672 if (!$bresv->target_resource) {
1673 my $filter = { type => $bresv->target_resource_type };
1674 my $attr_maps = [ booking::reservation_attr_value_map->search( reservation => $bresv->id) ];
1676 $filter->{attribute_values} = [ map { $_->attr_value } @$attr_maps ] if (@$attr_maps);
1678 $filter->{available} = [$bresv->start_time, $bresv->end_time];
1679 my $ses = OpenSRF::AppSession->create('open-ils.booking');
1680 $possible_resources = $ses->request('open-ils.booking.resources.filtered_id_list', undef, $filter)->gather(1);
1682 $possible_resources = $bresv->target_resource;
1685 my $all_resources = [ booking::resource->search( id => $possible_resources ) ];
1686 @$all_resources = grep { isTrue($_->type->transferable) || $_->owner.'' eq $bresv->pickup_lib.'' } @$all_resources;
1689 my @good_resources = ();
1691 for my $res (@$all_resources) {
1692 unless (isTrue($res->type->catalog_item)) {
1693 push @good_resources, $res;
1697 my $copy = [ asset::copy->search( deleted => 'f', barcode => $res->barcode )]->[0];
1700 push @good_resources, $res;
1704 # At this point, if we're just targeting one specific
1705 # resource, just succeed. We don't care about its present
1707 if ($bresv->target_resource) {
1708 push @good_resources, $res;
1712 if ($copy->status->id == 0 || $copy->status->id == 7) {
1713 push @good_resources, $res;
1717 if ($copy->status->id == 1) {
1718 my $circs = [ action::circulation->search_where(
1719 {target_copy => $copy->id, checkin_time => undef },
1720 { order_by => 'id DESC' }
1724 my $due_date = $circs->[0]->due_date;
1725 $due_date = $parser->parse_datetime( cleanse_ISO8601( $due_date ) );
1726 my $start_time = $parser->parse_datetime( cleanse_ISO8601( $bresv->start_time ) );
1727 if (DateTime->compare($start_time, $due_date) < 0) {
1728 $conflicts{$res->id} = $circs->[0]->to_fieldmapper;
1732 push @good_resources, $res;
1738 push @good_resources, $res if (isTrue($copy->status->holdable));
1741 # let 'em know we're still working
1742 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1744 # if we have no copies ...
1745 if (!@good_resources) {
1746 $log->info("\tNo resources available for targeting at all!\n");
1747 push @successes, { reservation => $bresv->id, eligible_copies => 0, error => 'NO_COPIES', conflicts => \%conflicts };
1750 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1754 $log->debug("\t".scalar(@good_resources)." resources available for targeting...");
1760 $_->owner == $bresv->pickup_lib
1764 $all_resources = [grep {$_->owner != $bresv->pickup_lib } @good_resources];
1765 # $all_copies is now a list of copies not at the pickup library
1767 my $best = shift @good_resources;
1768 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1771 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_resources)." resources");
1775 sort { $a->[0] <=> $b->[0] }
1777 [ actor::org_unit_proximity->search_where(
1778 { from_org => $bresv->pickup_lib.'', to_org => $_->owner.'' }
1784 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1786 $best = shift @$prox_list
1790 $bresv->update( { current_resource => ''.$best->id } );
1791 $log->debug("\tUpdating reservation [".$bresv->id."] with new 'current_resource' [".$best->id."] for reservation fulfillment.");
1794 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1795 $log->info("\tProcessing of bresv ".$bresv->id." complete.");
1798 { reservation => $bresv->id,
1799 current_resource => ($best ? $best->id : undef) };
1804 $log->error("Processing of bresv failed: $e");
1805 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1806 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1813 __PACKAGE__->register_method(
1814 api_name => 'open-ils.storage.booking.reservation.resource_targeter',
1816 method => 'reservation_targeter',
1821 my %cache = (titles => {}, cns => {});
1823 sub copy_hold_capture {
1828 if (!defined($cps)) {
1830 $cps = [ asset::copy->search( id => $hold->target ) ];
1831 } catch Error with {
1833 die "Could not retrieve initial volume list:\n\n$e\n";
1837 my @copies = grep { $_->holdable } @$cps;
1839 for (my $i = 0; $i < @$cps; $i++) {
1840 next unless $$cps[$i];
1842 my $cn = $cache{cns}{$copies[$i]->call_number};
1843 my $rec = $cache{titles}{$cn->record};
1844 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1845 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1846 $copies[$i] = undef if (
1848 !$self->{user_filter}->request(
1849 'open-ils.circ.permit_hold',
1850 $hold->to_fieldmapper, do {
1851 my $cp_fm = $copies[$i]->to_fieldmapper;
1852 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1853 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1854 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1857 { title => $rec->to_fieldmapper,
1858 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1859 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1862 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1865 @copies = grep { $_ } @copies;
1867 my $count = @copies;
1869 return unless ($count);
1871 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1874 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1875 for my $c (@copies) {
1876 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1878 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1884 sub choose_nearest_copy {
1886 my $prox_list = shift;
1888 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1889 next unless (ref $$prox_list[$p]);
1891 my @capturable = @{ $$prox_list[$p] };
1892 next unless (@capturable);
1894 my $rand = int(rand(scalar(@capturable)));
1896 while (my ($c) = splice(@capturable, $rand, 1)) {
1897 return $c if !exists($seen{$c->id}) && ( OpenILS::Utils::PermitHold::permit_copy_hold(
1898 { title => $c->call_number->record->to_fieldmapper,
1899 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1900 patron => $hold->usr->to_fieldmapper,
1901 copy => $c->to_fieldmapper,
1902 requestor => $hold->requestor->to_fieldmapper,
1903 request_lib => $hold->request_lib->to_fieldmapper,
1904 pickup_lib => $hold->pickup_lib->id,
1910 last unless(@capturable);
1911 $rand = int(rand(scalar(@capturable)));
1916 sub create_prox_list {
1921 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1924 for my $cp (@$copies) {
1925 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1926 next unless (defined($prox));
1928 my $copy_circ_lib = ''.$cp->circ_lib;
1929 # Fetch the weighting value for hold targeting, defaulting to 1
1930 $self->{target_weight}{$copy_circ_lib} ||= $actor->request(
1931 'open-ils.actor.ou_setting.ancestor_default' => $copy_circ_lib.'' => 'circ.holds.org_unit_target_weight'
1933 $self->{target_weight}{$copy_circ_lib} = $self->{target_weight}{$copy_circ_lib}{value} if (ref $self->{target_weight}{$copy_circ_lib});
1934 $self->{target_weight}{$copy_circ_lib} ||= 1;
1936 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1937 for my $w ( 1 .. $self->{target_weight}{$copy_circ_lib} ) {
1938 push @{$prox_list[$prox]}, $cp;
1944 sub volume_hold_capture {
1949 if (!defined($vols)) {
1951 $vols = [ asset::call_number->search( id => $hold->target ) ];
1952 $cache{cns}{$_->id} = $_ for (@$vols);
1953 } catch Error with {
1955 die "Could not retrieve initial volume list:\n\n$e\n";
1959 my @v_ids = map { $_->id } @$vols;
1963 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1965 } catch Error with {
1967 warn "Could not retrieve copy list:\n\n$e\n";
1970 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1973 sub title_hold_capture {
1978 if (!defined($titles)) {
1980 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1981 $cache{titles}{$_->id} = $_ for (@$titles);
1982 } catch Error with {
1984 die "Could not retrieve initial title list:\n\n$e\n";
1988 my @t_ids = map { $_->id } @$titles;
1991 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1993 } catch Error with {
1995 warn "Could not retrieve volume list:\n\n$e\n";
1998 $cache{cns}{$_->id} = $_ for (@$cn_list);
2000 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
2003 sub metarecord_hold_capture {
2009 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
2011 } catch Error with {
2013 die "Could not retrieve initial title list:\n\n$e\n";
2017 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
2019 $titles = [ biblio::record_entry->search( id => \@recs ) ];
2021 } catch Error with {
2023 die "Could not retrieve format-pruned title list:\n\n$e\n";
2027 $cache{titles}{$_->id} = $_ for (@$titles);
2028 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);