1 package OpenILS::Application::Storage::Publisher::action;
2 use base qw/OpenILS::Application::Storage::Publisher/;
3 use OpenSRF::Utils::Logger qw/:level/;
4 use OpenSRF::Utils qw/:datetime/;
5 use OpenSRF::AppSession;
6 use OpenSRF::EX qw/:try/;
7 use OpenILS::Utils::Fieldmapper;
8 use OpenILS::Utils::PermitHold;
10 use DateTime::Format::ISO8601;
11 use OpenILS::Utils::Penalty;
15 return 1 if ($v == 1);
16 return 1 if ($v =~ /^t/io);
17 return 1 if ($v =~ /^y/io);
21 my $parser = DateTime::Format::ISO8601->new;
22 my $log = 'OpenSRF::Utils::Logger';
24 sub open_noncat_circs {
29 my $a = action::non_cataloged_circulation->table;
30 my $c = config::non_cataloged_type->table;
35 JOIN $c c ON (a.item_type = c.id)
36 WHERE a.circ_time + c.circ_duration > current_timestamp
40 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
42 __PACKAGE__->register_method(
43 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
46 method => 'open_noncat_circs',
50 sub ou_hold_requests {
55 my $h_table = action::hold_request->table;
56 my $c_table = asset::copy->table;
57 my $o_table = actor::org_unit->table;
62 JOIN $c_table cp ON (cp.id = h.current_copy)
63 JOIN $o_table ou ON (ou.id = cp.circ_lib)
65 AND h.capture_time IS NULL
66 AND h.cancel_time IS NULL
67 AND (h.expire_time IS NULL OR h.expire_time > NOW())
68 ORDER BY h.request_time
71 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
74 $client->respond($_) for (
77 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
81 } @{ $sth->fetchall_arrayref }
85 __PACKAGE__->register_method(
86 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
90 method => 'ou_hold_requests',
96 my $upper_interval = shift || '1 millennium';
98 my $c_t = action::circulation->table;
100 if ($grace && $grace =~ /^\d+$/o) {
101 $grace = " - ($grace * (fine_interval))";
109 WHERE stop_fines IS NULL
110 AND due_date < ( CURRENT_TIMESTAMP $grace)
111 AND fine_interval < ?::INTERVAL
114 my $sth = action::circulation->db_Main->prepare_cached($sql);
115 $sth->execute($upper_interval);
117 return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
121 sub complete_reshelving {
126 local $OpenILS::Application::Storage::WRITE = 1;
128 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
129 unless (interval_to_seconds( $window ));
131 my $setting = actor::org_unit_setting->table;
132 my $circ = action::circulation->table;
133 my $cp = asset::copy->table;
140 FROM (SELECT cp.id, MAX(circ.checkin_time)
142 JOIN $circ circ ON (circ.target_copy = cp.id)
143 LEFT JOIN $setting setting
144 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
145 WHERE circ.checkin_time IS NOT NULL
148 HAVING MAX(circ.checkin_time) < NOW() - CAST( COALESCE( BTRIM( FIRST(setting.value),'"' ), ? ) AS INTERVAL)
153 LEFT JOIN $setting setting
154 ON (cp.circ_lib = setting.org_unit AND setting.name = 'circ.reshelving_complete.interval')
155 LEFT JOIN $circ circ ON (circ.target_copy = cp.id)
156 WHERE cp.status = 7 AND circ.id IS NULL
157 AND cp.create_date < NOW() - CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
161 my $sth = action::circulation->db_Main->prepare_cached($sql);
162 $sth->execute($window, $window);
167 __PACKAGE__->register_method(
168 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
171 method => 'complete_reshelving',
174 sub mark_longoverdue {
179 local $OpenILS::Application::Storage::WRITE = 1;
181 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
182 unless (interval_to_seconds( $window ));
184 my $setting = actor::org_unit_setting->table;
185 my $circ = action::circulation->table;
189 SET stop_fines = 'LONGOVERDUE',
190 stop_fines_time = now()
194 LEFT JOIN $setting setting
195 ON (circ.circ_lib = setting.org_unit AND setting.name = 'circ.long_overdue.interval')
196 WHERE circ.checkin_time IS NULL AND (stop_fines IS NULL OR stop_fines NOT IN ('LOST','LONGOVERDUE'))
197 AND AGE(circ.due_date) > CAST( COALESCE( BTRIM( setting.value,'"' ), ? ) AS INTERVAL)
201 my $sth = action::circulation->db_Main->prepare_cached($sql);
202 $sth->execute($window);
207 __PACKAGE__->register_method(
208 api_name => 'open-ils.storage.action.circulation.long_overdue',
211 method => 'mark_longoverdue',
214 sub auto_thaw_frozen_holds {
218 local $OpenILS::Application::Storage::WRITE = 1;
220 my $holds = action::hold_request->table;
222 my $sql = "UPDATE $holds SET frozen = FALSE WHERE frozen IS TRUE AND thaw_date < NOW();";
224 my $sth = action::hold_request->db_Main->prepare_cached($sql);
230 __PACKAGE__->register_method(
231 api_name => 'open-ils.storage.action.hold_request.thaw_expired_frozen',
235 method => 'auto_thaw_frozen_holds',
241 my $grace = shift || '';
243 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
248 __PACKAGE__->register_method(
249 api_name => 'open-ils.storage.action.circulation.overdue',
252 method => 'grab_overdue',
260 my $limit = int(shift()) || 10;
261 my $age = shift() || '0 seconds';
263 my $ids = action::hold_request->db_Main->selectcol_arrayref(<<" SQL", {}, $here, $cp, $age);
265 FROM action.hold_request h
266 JOIN actor.org_unit_proximity p ON (p.from_org = ? AND p.to_org = h.pickup_lib)
267 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
268 WHERE hm.target_copy = ?
269 AND (AGE(NOW(),h.request_time) >= CAST(? AS INTERVAL) OR p.prox = 0)
270 AND h.capture_time IS NULL
271 AND h.cancel_time IS NULL
272 AND (h.expire_time IS NULL OR h.expire_time > NOW())
273 AND h.frozen IS FALSE
276 CASE WHEN h.cut_in_line IS TRUE THEN 0 ELSE 1 END,
277 h.selection_depth DESC,
282 $client->respond( $_ ) for ( @$ids );
285 __PACKAGE__->register_method(
286 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
289 method => 'nearest_hold',
292 sub next_resp_group_id {
296 # XXX This is not replication safe!!!
298 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
299 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
303 __PACKAGE__->register_method(
304 api_name => 'open-ils.storage.action.survey_response.next_group_id',
306 method => 'next_resp_group_id',
309 sub patron_circ_summary {
314 return undef unless ($id);
315 my $c_table = action::circulation->table;
316 my $b_table = money::billing->table;
318 $log->debug("Retrieving patron summary for id $id", DEBUG);
320 my $select = <<" SQL";
321 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
323 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
325 AND c.xact_finish IS NULL
327 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
328 OR c.stop_fines IS NULL
332 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
334 __PACKAGE__->register_method(
335 api_name => 'open-ils.storage.action.circulation.patron_summary',
337 method => 'patron_circ_summary',
340 #XXX Fix stored proc calls
341 sub find_local_surveys {
346 return undef unless ($ou);
347 my $s_table = action::survey->table;
349 my $select = <<" SQL";
352 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
353 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
356 my $sth = action::survey->db_Main->prepare_cached($select);
359 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
363 __PACKAGE__->register_method(
364 api_name => 'open-ils.storage.action.survey.all',
367 method => 'find_local_surveys',
370 #XXX Fix stored proc calls
371 sub find_opac_surveys {
376 return undef unless ($ou);
377 my $s_table = action::survey->table;
379 my $select = <<" SQL";
382 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
383 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
387 my $sth = action::survey->db_Main->prepare_cached($select);
390 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
394 __PACKAGE__->register_method(
395 api_name => 'open-ils.storage.action.survey.opac',
398 method => 'find_opac_surveys',
405 my $limit = shift || 10;
406 my $offset = shift || 0;
408 return undef unless ($ou);
409 my $h_table = action::hold_request->table;
410 my $a_table = asset::copy->table;
411 my $ord_table = asset::copy_location_order->table;
413 my $idlist = 1 if ($self->api_name =~/id_list/o);
414 my $count = 1 if ($self->api_name =~/count$/o);
416 my $status_filter = '';
417 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
419 my $select = <<" SQL";
422 JOIN $a_table a ON (h.current_copy = a.id)
423 LEFT JOIN $ord_table ord ON (a.location = ord.location AND a.circ_lib = ord.org)
425 AND h.capture_time IS NULL
426 AND h.cancel_time IS NULL
427 AND (h.expire_time IS NULL OR h.expire_time > NOW())
429 ORDER BY CASE WHEN ord.position IS NOT NULL THEN ord.position ELSE 999 END, h.request_time
438 JOIN $a_table a ON (h.current_copy = a.id)
440 AND h.capture_time IS NULL
441 AND h.cancel_time IS NULL
442 AND (h.expire_time IS NULL OR h.expire_time > NOW())
447 my $sth = action::survey->db_Main->prepare_cached($select);
451 $client->respond( $sth->fetchall_arrayref()->[0][0] );
453 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
455 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
460 __PACKAGE__->register_method(
461 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.count',
465 "Returns a count of holds for a specific library's pull list.",
466 [ [org_unit => "The library's org id", "number"] ],
467 ['A count of holds for the stated library to pull ', 'number']
469 method => 'hold_pull_list',
471 __PACKAGE__->register_method(
472 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.current_copy_circ_lib.status_filtered.count',
476 "Returns a status filtered count of holds for a specific library's pull list.",
477 [ [org_unit => "The library's org id", "number"] ],
478 ['A status filtered count of holds for the stated library to pull ', 'number']
480 method => 'hold_pull_list',
482 __PACKAGE__->register_method(
483 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
487 "Returns the hold ids for a specific library's pull list.",
488 [ [org_unit => "The library's org id", "number"],
489 [limit => 'An optional page size, defaults to 10', 'number'],
490 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
492 ['A list of holds for the stated library to pull for', 'array']
494 method => 'hold_pull_list',
496 __PACKAGE__->register_method(
497 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
501 "Returns the holds for a specific library's pull list.",
502 [ [org_unit => "The library's org id", "number"],
503 [limit => 'An optional page size, defaults to 10', 'number'],
504 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
506 ['A list of holds for the stated library to pull for', 'array']
508 method => 'hold_pull_list',
510 __PACKAGE__->register_method(
511 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
515 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
516 [ [org_unit => "The library's org id", "number"],
517 [limit => 'An optional page size, defaults to 10', 'number'],
518 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
520 ['A list of holds for the stated library to pull for', 'array']
522 method => 'hold_pull_list',
524 __PACKAGE__->register_method(
525 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
529 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
530 [ [org_unit => "The library's org id", "number"],
531 [limit => 'An optional page size, defaults to 10', 'number'],
532 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
534 ['A list of holds for the stated library to pull for', 'array']
536 method => 'hold_pull_list',
539 sub find_optional_surveys {
544 return undef unless ($ou);
545 my $s_table = action::survey->table;
547 my $select = <<" SQL";
550 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
551 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
552 AND s.required IS FALSE;
555 my $sth = action::survey->db_Main->prepare_cached($select);
558 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
562 __PACKAGE__->register_method(
563 api_name => 'open-ils.storage.action.survey.optional',
566 method => 'find_optional_surveys',
569 sub find_required_surveys {
574 return undef unless ($ou);
575 my $s_table = action::survey->table;
577 my $select = <<" SQL";
580 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
581 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
582 AND s.required IS TRUE;
585 my $sth = action::survey->db_Main->prepare_cached($select);
588 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
592 __PACKAGE__->register_method(
593 api_name => 'open-ils.storage.action.survey.required',
596 method => 'find_required_surveys',
599 sub find_usr_summary_surveys {
604 return undef unless ($ou);
605 my $s_table = action::survey->table;
607 my $select = <<" SQL";
610 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
611 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
612 AND s.usr_summary IS TRUE;
615 my $sth = action::survey->db_Main->prepare_cached($select);
618 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
622 __PACKAGE__->register_method(
623 api_name => 'open-ils.storage.action.survey.usr_summary',
626 method => 'find_usr_summary_surveys',
635 my $overbill = shift;
637 local $OpenILS::Application::Storage::WRITE = 1;
641 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
643 push @circs, overdue_circs($grace);
646 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
648 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
652 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
653 $log->debug("Cleaning up after previous transaction\n");
654 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
656 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
657 $log->info("Processing circ ".$c->id."...\n");
660 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
662 my $due = $due_dt->epoch;
665 my $fine_interval = $c->fine_interval;
666 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
667 $fine_interval = interval_to_seconds( $fine_interval );
669 if ( $fine_interval >= interval_to_seconds('1d') ) {
671 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
672 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
675 $due -= ($due % $fine_interval) + $tz_offset_s;
676 $now -= ($now % $fine_interval) + $tz_offset_s;
680 "ARG! Overdue circulation ".$c->id.
681 " for item ".$c->target_copy.
682 " (user ".$c->usr.").\n".
683 "\tItem was due on or before: ".localtime($due)."\n");
685 my @fines = money::billing->search_where(
688 billing_ts => { '>' => $c->due_date } },
689 { order_by => 'billing_ts DESC'}
693 my $fine = $fines[$f_idx] if (@fines);
695 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
698 my $current_fine_total = 0;
699 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
703 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
704 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
706 $log->info( "Potential first billing for circ ".$c->id );
710 if (my $h = $hoo{$c->circ_lib}) {
712 $log->info( "Circ lib has an hours-of-operation entry" );
713 # find the day after the due date...
714 $due_dt = $due_dt->add( days => 1 );
716 # get the day of the week for that day...
717 my $dow = $due_dt->day_of_week_0;
718 my $dow_open = "dow_${dow}_open";
719 my $dow_close = "dow_${dow}_close";
722 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
723 # if the circ lib is closed, add a day to the grace period...
726 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
727 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
729 $due_dt = $due_dt->add( days => 1 );
730 $dow = $due_dt->day_of_week_0;
731 $dow_open = "dow_${dow}_open";
732 $dow_close = "dow_${dow}_close";
736 # and check for up to a week
737 last if ($count > 6);
744 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
745 if ($pending_fine_count < 1 + $grace) {
746 $client->respond( "\tNo fines to create. " );
747 if ($grace && $now < $due + $fine_interval * $grace) {
748 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
749 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
751 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
756 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
758 my $recurring_fine = int($c->recurring_fine * 100);
759 my $max_fine = int($c->max_fine * 100);
761 my ($latest_billing_ts, $latest_amount) = ('',0);
762 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
764 if ($current_fine_total >= $max_fine) {
765 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
767 "\tMaximum fine level of ".$c->max_fine.
768 " reached for this circulation.\n".
769 "\tNo more fines will be generated.\n" );
773 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
775 my $dow = $billing_ts->day_of_week_0();
776 my $dow_open = "dow_${dow}_open";
777 my $dow_close = "dow_${dow}_close";
779 if (my $h = $hoo{$c->circ_lib}) {
780 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
783 my $timestamptz = $billing_ts->strftime('%FT%T%z');
784 my @cl = actor::org_unit::closed_date->search_where(
785 { close_start => { '<=' => $timestamptz },
786 close_end => { '>=' => $timestamptz },
787 org_unit => $c->circ_lib }
791 $current_fine_total += $recurring_fine;
792 $latest_amount += $recurring_fine;
793 $latest_billing_ts = $timestamptz;
795 money::billing->create(
797 note => "System Generated Overdue Fine",
798 billing_type => "Overdue materials",
800 amount => sprintf('%0.2f', $recurring_fine/100),
801 billing_ts => $timestamptz,
807 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
808 if ($latest_billing_ts and $latest_amount);
810 $self->method_lookup('open-ils.storage.transaction.commit')->run;
814 # Caluclate penalties inline
815 OpenILS::Utils::Penalty->calculate_penalties(
816 undef, $c->usr->to_fieldmapper->id.'', $c->circ_lib->to_fieldmapper->id.'');
820 # Calculate penalties with an aysnc call to the penalty server. This approach
821 # may lead to duplicate penalties since multiple penalty processes for a
822 # given user may be running at the same time. Leave this here for reference
823 # in case we later find that asyc calls are needed in some environments.
825 'open-ils.penalty.patron_penalty.calculate',
826 { patronid => ''.$c->usr,
827 context_org => ''.$c->circ_lib,
836 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
837 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
838 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
839 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
843 __PACKAGE__->register_method(
844 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
847 method => 'generate_fines',
852 sub new_hold_copy_targeter {
855 my $check_expire = shift;
856 my $one_hold = shift;
858 local $OpenILS::Application::Storage::WRITE = 1;
860 $self->{target_weight} = {};
866 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
867 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
868 } elsif ( $check_expire ) {
870 # what's the retarget time threashold?
872 $check_expire ||= '12h';
873 $check_expire = interval_to_seconds( $check_expire );
875 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
878 my $expire_threshold = sprintf(
879 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
880 $year, $mon, $mday, $hour, $min, $sec
883 # find all the holds holds needing retargeting
884 $holds = [ action::hold_request->search_where(
885 { capture_time => undef,
886 fulfillment_time => undef,
887 cancel_time => undef,
889 prev_check_time => { '<=' => $expire_threshold },
891 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
893 # find all the holds holds needing first time targeting
894 push @$holds, action::hold_request->search(
895 capture_time => undef,
896 fulfillment_time => undef,
897 prev_check_time => undef,
899 cancel_time => undef,
900 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
903 # find all the holds holds needing first time targeting ONLY
904 $holds = [ action::hold_request->search(
905 capture_time => undef,
906 fulfillment_time => undef,
907 prev_check_time => undef,
908 cancel_time => undef,
910 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
914 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
917 my @closed = actor::org_unit::closed_date->search_where(
918 { close_start => { '<=', 'now' },
919 close_end => { '>=', 'now' } }
924 # $check_expire, if it exists, was already converted to seconds
925 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
929 my $next_check_time = sprintf(
930 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
931 $year, $mon, $mday, $hour, $min, $sec
935 my @closed_at_next = actor::org_unit::closed_date->search_where(
936 { close_start => { '<=', $next_check_time },
937 close_end => { '>=', $next_check_time } }
941 for my $c_at_n (@closed_at_next) {
942 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
943 push @new_closed, $c_at_n;
946 @closed = @new_closed;
950 my $actor = OpenSRF::AppSession->create('open-ils.actor');
952 for my $hold (@$holds) {
954 #start a transaction if needed
955 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
956 $log->debug("Cleaning up after previous transaction\n");
957 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
959 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
960 $log->info("Processing hold ".$hold->id."...\n");
962 #first, re-fetch the hold, to make sure it's not captured already
963 $hold->remove_from_object_index();
964 $hold = action::hold_request->retrieve( $hold->id );
966 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
968 # remove old auto-targeting maps
969 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
970 $_->delete for (@oldmaps);
972 if ($hold->expire_time) {
973 my $ex_time = $parser->parse_datetime( clense_ISO8601( $hold->expire_time ) );
974 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
976 # cancel cause = un-targeted expiration
977 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
978 $self->method_lookup('open-ils.storage.transaction.commit')->run;
980 # tell A/T the hold was cancelled
981 my $fm_hold = $hold->to_fieldmapper;
982 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
983 $ses->request('open-ils.trigger.event.autocreate',
984 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
992 # find filters for MR holds
993 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
995 # find all the potential copies
996 if ($hold->hold_type eq 'M') {
999 metabib::record_descriptor
1003 isTrue($_->deleted) ? () : ($_->id)
1004 } metabib::metarecord->retrieve($hold->target)->source_records
1006 ( $types ? (item_type => [split '', $types]) : () ),
1007 ( $formats ? (item_form => [split '', $formats]) : () ),
1008 ( $lang ? (item_lang => $lang) : () ),
1012 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1013 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
1015 for my $cn ( @{ $rtree->call_numbers } ) {
1017 asset::copy->search_where(
1018 { id => [map {$_->id} @{ $cn->copies }],
1020 ) if ($cn && @{ $cn->copies });
1023 } elsif ($hold->hold_type eq 'T') {
1025 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
1026 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1029 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
1033 for my $cn ( @{ $rtree->call_numbers } ) {
1035 asset::copy->search_where(
1036 { id => [map {$_->id} @{ $cn->copies }],
1038 ) if ($cn && @{ $cn->copies });
1040 } elsif ($hold->hold_type eq 'V') {
1042 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1043 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1046 asset::copy->search_where(
1047 { id => [map {$_->id} @{ $vtree->copies }],
1049 ) if ($vtree && @{ $vtree->copies });
1051 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1052 my $_cp = asset::copy->retrieve($hold->target);
1053 push @$all_copies, $_cp if $_cp;
1057 @$all_copies = grep { isTrue($_->status->holdable) &&
1058 isTrue($_->location->holdable) &&
1059 isTrue($_->holdable) &&
1060 !isTrue($_->deleted) &&
1061 isTrue($hold->mint_condition) ? isTrue($_->mint_condition) : 1
1064 # let 'em know we're still working
1065 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1067 # if we have no copies ...
1068 if (!ref $all_copies || !@$all_copies) {
1069 $log->info("\tNo copies available for targeting at all!\n");
1070 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1072 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1073 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1077 my $copy_count = @$all_copies;
1079 # map the potentials, so that we can pick up checkins
1080 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1081 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1082 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1083 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1085 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1088 for my $c (@$all_copies) {
1090 next if ($c->id eq $hold->current_copy);
1092 # circ lib is closed
1093 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1095 # target of another hold
1096 next if (action::hold_request
1098 { current_copy => $c->id,
1099 fulfillment_time => undef,
1100 cancel_time => undef,
1105 # we passed all three, keep it
1106 push @good_copies, $c if ($c);
1107 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1110 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1112 my $old_best = $hold->current_copy;
1113 $hold->update({ current_copy => undef }) if ($old_best);
1115 if (!scalar(@good_copies)) {
1116 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1117 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1118 # the old copy is still available
1119 $log->debug("\tPushing current_copy back onto the targeting list");
1120 push @good_copies, $old_best;
1122 # oops, old copy is not available
1123 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1124 $hold->update( { prev_check_time => 'today' } );
1125 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1126 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1135 $_->circ_lib == $hold->pickup_lib
1139 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1140 # $all_copies is now a list of copies not at the pickup library
1142 my $best = choose_nearest_copy($hold, $prox_list);
1143 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1146 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1148 my $max_loops = $actor->request(
1149 'open-ils.actor.ou_setting.ancestor_default' => $hold->pickup_lib.'' => 'circ.holds.max_org_unit_target_loops'
1152 if (defined($max_loops)) {
1153 my %circ_lib_map = map { $_->circ_lib => 1 } @$all_copies;
1154 my $circ_lib_list = [keys %circ_lib_map];
1156 my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
1158 # Grab the "biggest" loop for this hold so far
1159 my $current_loop = $cstore->request(
1160 'open-ils.cstore.json_query',
1162 select => { aufhmxl => ['max'] },
1164 where => { hold => $hold->id}
1168 $current_loop = $current_loop->{max} if ($current_loop);
1169 $current_loop ||= 1;
1171 my $exclude_list = $cstore->request(
1172 'open-ils.cstore.json_query.atomic',
1174 select => { aufhol => [circ_lib] },
1176 where => { hold => $hold->id}
1181 if ($exclude_list && @$exclude_list) {
1182 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1183 # check to see if we've used up every library in the potentials list
1184 for my $l ( @$circ_lib_list ) {
1186 for my $ex ( @$exclude_list ) {
1192 push(@keepers, $l) if ($keep);
1195 @keepers = @$circ_lib_list;
1198 $current_loop++ if (!@keepers);
1200 if ($max_loops && $max_loops <= $current_loop) {
1201 # We haven't exceeded max_loops yet
1203 for my $cp ( @$all_copies ) {
1204 push (@keeper_copies, $cp) if ( grep { $_ eq $cp->circ_lib } @keepers );
1207 # We have, and should remove potentials and cancel the hold
1208 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1209 $_->delete for (@oldmaps);
1211 # cancel cause = un-targeted expiration
1212 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1213 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1215 # tell A/T the hold was cancelled
1216 my $fm_hold = $hold->to_fieldmapper;
1217 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1218 $ses->request('open-ils.trigger.event.autocreate',
1219 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1225 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1227 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1229 $best = choose_nearest_copy($hold, $prox_list);
1232 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1234 # hold wasn't fulfilled, record the fact
1236 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1237 action::unfulfilled_hold_list->create(
1238 { hold => ''.$hold->id,
1239 current_copy => ''.$old_best->id,
1240 circ_lib => ''.$old_best->circ_lib,
1245 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1246 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1249 action::hold_request
1251 { current_copy => $old_best->id,
1252 fulfillment_time => undef,
1253 cancel_time => undef,
1257 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1258 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1260 $hold->update( { prev_check_time => 'now' } );
1261 $log->info( "\tThere were no targetable copies for the hold" );
1264 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1265 $log->info("\tProcessing of hold ".$hold->id." complete.");
1268 { hold => $hold->id,
1269 old_target => ($old_best ? $old_best->id : undef),
1270 eligible_copies => $copy_count,
1271 target => ($best ? $best->id : undef) };
1276 $log->error("Processing of hold failed: $e");
1277 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1278 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1285 __PACKAGE__->register_method(
1286 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1288 method => 'new_hold_copy_targeter',
1293 my %cache = (titles => {}, cns => {});
1294 sub hold_copy_targeter {
1297 my $check_expire = shift;
1298 my $one_hold = shift;
1300 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1301 $self->{user_filter}->connect;
1302 $self->{client} = $client;
1305 $check_expire ||= '12h';
1306 $check_expire = interval_to_seconds( $check_expire );
1308 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1311 my $expire_threshold = sprintf(
1312 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1313 $year, $mon, $mday, $hour, $min, $sec
1317 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1319 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1323 %cache = (titles => {}, cns => {});
1327 $holds = [ action::hold_request->search(id => $one_hold) ];
1329 $holds = [ action::hold_request->search_where(
1330 { capture_time => undef,
1331 prev_check_time => { '<=' => $expire_threshold },
1333 { order_by => 'request_time,prev_check_time' } ) ];
1334 push @$holds, action::hold_request->search_where(
1335 { capture_time => undef,
1336 prev_check_time => undef,
1338 { order_by => 'request_time' } );
1340 } catch Error with {
1342 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1345 for my $hold (@$holds) {
1347 #action::hold_request->db_Main->begin_work;
1348 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1349 $client->respond("Cleaning up after previous transaction\n");
1350 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1352 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1353 $client->respond("Processing hold ".$hold->id."...\n");
1357 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1358 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1360 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1361 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1363 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1364 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1366 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1368 unless (ref $copies || !@$copies) {
1369 $client->respond("\tNo copies available for targeting at all!\n");
1373 for my $c (@$copies) {
1374 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1375 push @good_copies, $c if ($c);
1378 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1380 my $old_best = $hold->current_copy;
1381 $hold->update({ current_copy => undef });
1383 if (!scalar(@good_copies)) {
1384 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1385 if ( $old_best && grep {$_->id == $hold->current_copy} @$copies ) {
1386 $client->respond("\tPushing current_copy back onto the targeting list\n");
1387 push @good_copies, asset::copy->retrieve( $old_best );
1389 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1395 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1396 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1398 my $best = choose_nearest_copy($hold, $prox_list);
1401 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1402 $best = choose_nearest_copy($hold, $prox_list);
1406 # hold wasn't fulfilled, record the fact
1408 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1409 action::unfulfilled_hold_list->create(
1410 { hold => ''.$hold->id,
1411 current_copy => ''.$old_best->id,
1412 circ_lib => ''.$old_best->circ_lib,
1417 $hold->update( { current_copy => ''.$best->id } );
1418 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1421 $hold->update( { prev_check_time => 'now' } );
1422 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1424 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1425 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1427 #action::hold_request->dbi_commit;
1431 $log->error("Processing of hold failed: $e");
1432 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1433 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1434 #action::hold_request->dbi_rollback;
1438 $self->{user_filter}->disconnect;
1439 $self->{user_filter}->finish;
1440 delete $$self{user_filter};
1443 #__PACKAGE__->register_method(
1444 # api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1447 # method => 'hold_copy_targeter',
1451 sub copy_hold_capture {
1456 if (!defined($cps)) {
1458 $cps = [ asset::copy->search( id => $hold->target ) ];
1459 } catch Error with {
1461 die "Could not retrieve initial volume list:\n\n$e\n";
1465 my @copies = grep { $_->holdable } @$cps;
1467 for (my $i = 0; $i < @$cps; $i++) {
1468 next unless $$cps[$i];
1470 my $cn = $cache{cns}{$copies[$i]->call_number};
1471 my $rec = $cache{titles}{$cn->record};
1472 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1473 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1474 $copies[$i] = undef if (
1476 !$self->{user_filter}->request(
1477 'open-ils.circ.permit_hold',
1478 $hold->to_fieldmapper, do {
1479 my $cp_fm = $copies[$i]->to_fieldmapper;
1480 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1481 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1482 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1485 { title => $rec->to_fieldmapper,
1486 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1487 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1490 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1493 @copies = grep { $_ } @copies;
1495 my $count = @copies;
1497 return unless ($count);
1499 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1502 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1503 for my $c (@copies) {
1504 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1506 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1512 sub choose_nearest_copy {
1514 my $prox_list = shift;
1516 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1517 next unless (ref $$prox_list[$p]);
1519 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1520 next unless (@capturable);
1522 my $rand = int(rand(scalar(@capturable)));
1523 while (my ($c) = splice(@capturable,$rand)) {
1524 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1525 { title => $c->call_number->record->to_fieldmapper,
1526 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1527 patron => $hold->usr->to_fieldmapper,
1528 copy => $c->to_fieldmapper,
1529 requestor => $hold->requestor->to_fieldmapper,
1530 request_lib => $hold->request_lib->to_fieldmapper,
1531 pickup_lib => $hold->pickup_lib->id,
1535 last unless(@capturable);
1536 $rand = int(rand(scalar(@capturable)));
1541 sub create_prox_list {
1546 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1549 for my $cp (@$copies) {
1550 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1551 next unless (defined($prox));
1553 # Fetch the weighting value for hold targeting, defaulting to 1
1554 $self->{target_weight}{$lib} ||= $actor->request(
1555 'open-ils.actor.ou_setting.ancestor_default' => $lib.'' => 'circ.holds.org_unit_target_weight'
1558 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1559 for my $w ( 1 .. $self->{target_weight}{$lib} ) {
1560 push @{$prox_list[$prox]}, $cp;
1566 sub volume_hold_capture {
1571 if (!defined($vols)) {
1573 $vols = [ asset::call_number->search( id => $hold->target ) ];
1574 $cache{cns}{$_->id} = $_ for (@$vols);
1575 } catch Error with {
1577 die "Could not retrieve initial volume list:\n\n$e\n";
1581 my @v_ids = map { $_->id } @$vols;
1585 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1587 } catch Error with {
1589 warn "Could not retrieve copy list:\n\n$e\n";
1592 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1595 sub title_hold_capture {
1600 if (!defined($titles)) {
1602 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1603 $cache{titles}{$_->id} = $_ for (@$titles);
1604 } catch Error with {
1606 die "Could not retrieve initial title list:\n\n$e\n";
1610 my @t_ids = map { $_->id } @$titles;
1613 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1615 } catch Error with {
1617 warn "Could not retrieve volume list:\n\n$e\n";
1620 $cache{cns}{$_->id} = $_ for (@$cn_list);
1622 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1625 sub metarecord_hold_capture {
1631 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1633 } catch Error with {
1635 die "Could not retrieve initial title list:\n\n$e\n";
1639 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1641 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1643 } catch Error with {
1645 die "Could not retrieve format-pruned title list:\n\n$e\n";
1649 $cache{titles}{$_->id} = $_ for (@$titles);
1650 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);