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;
412 my $idlist = 1 if ($self->api_name =~/id_list/o);
414 my $status_filter = '';
415 $status_filter = 'AND a.status IN (0,7)' if ($self->api_name =~/status_filtered/o);
417 my $select = <<" SQL";
420 JOIN $a_table a ON (h.current_copy = a.id)
422 AND h.capture_time IS NULL
423 AND h.cancel_time IS NULL
424 AND (h.expire_time IS NULL OR h.expire_time > NOW())
426 ORDER BY h.request_time ASC
431 my $sth = action::survey->db_Main->prepare_cached($select);
435 $client->respond( $_->{id} ) for ( $sth->fetchall_hash );
437 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
442 __PACKAGE__->register_method(
443 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib',
447 "Returns the hold ids for a specific library's pull list.",
448 [ [org_unit => "The library's org id", "number"],
449 [limit => 'An optional page size, defaults to 10', 'number'],
450 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
452 ['A list of holds for the stated library to pull for', 'array']
454 method => 'hold_pull_list',
456 __PACKAGE__->register_method(
457 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
461 "Returns the holds for a specific library's pull list.",
462 [ [org_unit => "The library's org id", "number"],
463 [limit => 'An optional page size, defaults to 10', 'number'],
464 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
466 ['A list of holds for the stated library to pull for', 'array']
468 method => 'hold_pull_list',
470 __PACKAGE__->register_method(
471 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.id_list.current_copy_circ_lib.status_filtered',
475 "Returns the hold ids for a specific library's pull list that are definitely in that library, based on status.",
476 [ [org_unit => "The library's org id", "number"],
477 [limit => 'An optional page size, defaults to 10', 'number'],
478 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
480 ['A list of holds for the stated library to pull for', 'array']
482 method => 'hold_pull_list',
484 __PACKAGE__->register_method(
485 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib.status_filtered',
489 "Returns the holds for a specific library's pull list that are definitely in that library, based on status.",
490 [ [org_unit => "The library's org id", "number"],
491 [limit => 'An optional page size, defaults to 10', 'number'],
492 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
494 ['A list of holds for the stated library to pull for', 'array']
496 method => 'hold_pull_list',
499 sub find_optional_surveys {
504 return undef unless ($ou);
505 my $s_table = action::survey->table;
507 my $select = <<" SQL";
510 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
511 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
512 AND s.required IS FALSE;
515 my $sth = action::survey->db_Main->prepare_cached($select);
518 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
522 __PACKAGE__->register_method(
523 api_name => 'open-ils.storage.action.survey.optional',
526 method => 'find_optional_surveys',
529 sub find_required_surveys {
534 return undef unless ($ou);
535 my $s_table = action::survey->table;
537 my $select = <<" SQL";
540 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
541 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
542 AND s.required IS TRUE;
545 my $sth = action::survey->db_Main->prepare_cached($select);
548 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
552 __PACKAGE__->register_method(
553 api_name => 'open-ils.storage.action.survey.required',
556 method => 'find_required_surveys',
559 sub find_usr_summary_surveys {
564 return undef unless ($ou);
565 my $s_table = action::survey->table;
567 my $select = <<" SQL";
570 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
571 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
572 AND s.usr_summary IS TRUE;
575 my $sth = action::survey->db_Main->prepare_cached($select);
578 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
582 __PACKAGE__->register_method(
583 api_name => 'open-ils.storage.action.survey.usr_summary',
586 method => 'find_usr_summary_surveys',
595 my $overbill = shift;
597 local $OpenILS::Application::Storage::WRITE = 1;
601 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
603 push @circs, overdue_circs($grace);
606 my %hoo = map { ( $_->id => $_ ) } actor::org_unit::hours_of_operation->retrieve_all;
608 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
612 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
613 $log->debug("Cleaning up after previous transaction\n");
614 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
616 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
617 $log->info("Processing circ ".$c->id."...\n");
620 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
622 my $due = $due_dt->epoch;
625 my $fine_interval = $c->fine_interval;
626 $fine_interval =~ s/(\d{2}):(\d{2}):(\d{2})/$1 h $2 m $3 s/o;
627 $fine_interval = interval_to_seconds( $fine_interval );
629 if ( $fine_interval >= interval_to_seconds('1d') ) {
631 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
632 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
635 $due -= ($due % $fine_interval) + $tz_offset_s;
636 $now -= ($now % $fine_interval) + $tz_offset_s;
640 "ARG! Overdue circulation ".$c->id.
641 " for item ".$c->target_copy.
642 " (user ".$c->usr.").\n".
643 "\tItem was due on or before: ".localtime($due)."\n");
645 my @fines = money::billing->search_where(
648 billing_ts => { '>' => $c->due_date } },
649 { order_by => 'billing_ts DESC'}
653 my $fine = $fines[$f_idx] if (@fines);
655 $fine = $fines[++$f_idx] while ($fine and $fine->voided);
658 my $current_fine_total = 0;
659 $current_fine_total += int($_->amount * 100) for (grep { $_ and !$_->voided } @fines);
663 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
664 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
666 $log->info( "Potential first billing for circ ".$c->id );
670 if (my $h = $hoo{$c->circ_lib}) {
672 $log->info( "Circ lib has an hours-of-operation entry" );
673 # find the day after the due date...
674 $due_dt = $due_dt->add( days => 1 );
676 # get the day of the week for that day...
677 my $dow = $due_dt->day_of_week_0;
678 my $dow_open = "dow_${dow}_open";
679 my $dow_close = "dow_${dow}_close";
682 while ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00' ) {
683 # if the circ lib is closed, add a day to the grace period...
686 $log->info( "Grace period for circ ".$c->id." extended to $grace intervals" );
687 $log->info( "Day of week $dow open $dow_open, close $dow_close" );
689 $due_dt = $due_dt->add( days => 1 );
690 $dow = $due_dt->day_of_week_0;
691 $dow_open = "dow_${dow}_open";
692 $dow_close = "dow_${dow}_close";
696 # and check for up to a week
697 last if ($count > 6);
704 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval );
705 if ($pending_fine_count < 1 + $grace) {
706 $client->respond( "\tNo fines to create. " );
707 if ($grace && $now < $due + $fine_interval * $grace) {
708 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
709 $log->info( "Circ ".$c->id." is still inside grace period of: $grace [". seconds_to_interval( $fine_interval * $grace).']' );
711 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
716 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
718 my $recuring_fine = int($c->recuring_fine * 100);
719 my $max_fine = int($c->max_fine * 100);
721 my ($latest_billing_ts, $latest_amount) = ('',0);
722 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
724 if ($current_fine_total >= $max_fine) {
725 $c->update({stop_fines => 'MAXFINES', stop_fines_time => 'now'});
727 "\tMaximum fine level of ".$c->max_fine.
728 " reached for this circulation.\n".
729 "\tNo more fines will be generated.\n" );
733 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
735 my $dow = $billing_ts->day_of_week_0();
736 my $dow_open = "dow_${dow}_open";
737 my $dow_close = "dow_${dow}_close";
739 if (my $h = $hoo{$c->circ_lib}) {
740 next if ( $h->$dow_open eq '00:00:00' and $h->$dow_close eq '00:00:00');
743 my $timestamptz = $billing_ts->strftime('%FT%T%z');
744 my @cl = actor::org_unit::closed_date->search_where(
745 { close_start => { '<=' => $timestamptz },
746 close_end => { '>=' => $timestamptz },
747 org_unit => $c->circ_lib }
751 $current_fine_total += $recuring_fine;
752 $latest_amount += $recuring_fine;
753 $latest_billing_ts = $timestamptz;
755 money::billing->create(
757 note => "System Generated Overdue Fine",
758 billing_type => "Overdue materials",
760 amount => sprintf('%0.2f', $recuring_fine/100),
761 billing_ts => $timestamptz,
767 $client->respond( "\t\tAdding fines totaling $latest_amount for overdue up to $latest_billing_ts\n" )
768 if ($latest_billing_ts and $latest_amount);
770 $self->method_lookup('open-ils.storage.transaction.commit')->run;
774 # Caluclate penalties inline
775 OpenILS::Utils::Penalty->calculate_penalties(
776 undef, $c->usr->to_fieldmapper->id.'', $c->circ_lib->to_fieldmapper->id.'');
780 # Calculate penalties with an aysnc call to the penalty server. This approach
781 # may lead to duplicate penalties since multiple penalty processes for a
782 # given user may be running at the same time. Leave this here for reference
783 # in case we later find that asyc calls are needed in some environments.
785 'open-ils.penalty.patron_penalty.calculate',
786 { patronid => ''.$c->usr,
787 context_org => ''.$c->circ_lib,
796 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
797 $log->error("Error processing overdue circulation [".$c->id."]:\n$e\n");
798 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
799 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
803 __PACKAGE__->register_method(
804 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
807 method => 'generate_fines',
812 sub new_hold_copy_targeter {
815 my $check_expire = shift;
816 my $one_hold = shift;
818 local $OpenILS::Application::Storage::WRITE = 1;
820 $self->{target_weight} = {};
826 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
827 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
828 } elsif ( $check_expire ) {
830 # what's the retarget time threashold?
832 $check_expire ||= '12h';
833 $check_expire = interval_to_seconds( $check_expire );
835 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
838 my $expire_threshold = sprintf(
839 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
840 $year, $mon, $mday, $hour, $min, $sec
843 # find all the holds holds needing retargeting
844 $holds = [ action::hold_request->search_where(
845 { capture_time => undef,
846 fulfillment_time => undef,
847 cancel_time => undef,
849 prev_check_time => { '<=' => $expire_threshold },
851 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time,prev_check_time' } ) ];
853 # find all the holds holds needing first time targeting
854 push @$holds, action::hold_request->search(
855 capture_time => undef,
856 fulfillment_time => undef,
857 prev_check_time => undef,
859 cancel_time => undef,
860 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } );
863 # find all the holds holds needing first time targeting ONLY
864 $holds = [ action::hold_request->search(
865 capture_time => undef,
866 fulfillment_time => undef,
867 prev_check_time => undef,
868 cancel_time => undef,
870 { order_by => 'CASE WHEN hold_type = \'F\' THEN 0 ELSE 1 END, selection_depth DESC, request_time' } ) ];
874 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
877 my @closed = actor::org_unit::closed_date->search_where(
878 { close_start => { '<=', 'now' },
879 close_end => { '>=', 'now' } }
884 # $check_expire, if it exists, was already converted to seconds
885 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() + $check_expire);
889 my $next_check_time = sprintf(
890 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
891 $year, $mon, $mday, $hour, $min, $sec
895 my @closed_at_next = actor::org_unit::closed_date->search_where(
896 { close_start => { '<=', $next_check_time },
897 close_end => { '>=', $next_check_time } }
901 for my $c_at_n (@closed_at_next) {
902 if (grep { ''.$_->org_unit eq ''.$c_at_n->org_unit } @closed) {
903 push @new_closed, $c_at_n;
906 @closed = @new_closed;
910 my $actor = OpenSRF::AppSession->create('open-ils.actor');
912 for my $hold (@$holds) {
914 #start a transaction if needed
915 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
916 $log->debug("Cleaning up after previous transaction\n");
917 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
919 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
920 $log->info("Processing hold ".$hold->id."...\n");
922 #first, re-fetch the hold, to make sure it's not captured already
923 $hold->remove_from_object_index();
924 $hold = action::hold_request->retrieve( $hold->id );
926 die "OK\n" if (!$hold or $hold->capture_time or $hold->cancel_time);
928 # remove old auto-targeting maps
929 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
930 $_->delete for (@oldmaps);
932 if ($hold->expire_time) {
933 my $ex_time = $parser->parse_datetime( clense_ISO8601( $hold->expire_time ) );
934 if ( DateTime->compare($ex_time, DateTime->now) < 0 ) {
936 # cancel cause = un-targeted expiration
937 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
938 $self->method_lookup('open-ils.storage.transaction.commit')->run;
940 # tell A/T the hold was cancelled
941 my $fm_hold = $hold->to_fieldmapper;
942 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
943 $ses->request('open-ils.trigger.event.autocreate',
944 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
952 # find filters for MR holds
953 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
955 # find all the potential copies
956 if ($hold->hold_type eq 'M') {
959 metabib::record_descriptor
963 isTrue($_->deleted) ? () : ($_->id)
964 } metabib::metarecord->retrieve($hold->target)->source_records
966 ( $types ? (item_type => [split '', $types]) : () ),
967 ( $formats ? (item_form => [split '', $formats]) : () ),
968 ( $lang ? (item_lang => $lang) : () ),
972 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
973 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
975 for my $cn ( @{ $rtree->call_numbers } ) {
977 asset::copy->search_where(
978 { id => [map {$_->id} @{ $cn->copies }],
980 ) if ($cn && @{ $cn->copies });
983 } elsif ($hold->hold_type eq 'T') {
985 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
986 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
989 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
993 for my $cn ( @{ $rtree->call_numbers } ) {
995 asset::copy->search_where(
996 { id => [map {$_->id} @{ $cn->copies }],
998 ) if ($cn && @{ $cn->copies });
1000 } elsif ($hold->hold_type eq 'V') {
1002 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
1003 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
1006 asset::copy->search_where(
1007 { id => [map {$_->id} @{ $vtree->copies }],
1009 ) if ($vtree && @{ $vtree->copies });
1011 } elsif ($hold->hold_type eq 'C' || $hold->hold_type eq 'R' || $hold->hold_type eq 'F') {
1012 my $_cp = asset::copy->retrieve($hold->target);
1013 push @$all_copies, $_cp if $_cp;
1017 @$all_copies = grep { isTrue($_->status->holdable) &&
1018 isTrue($_->location->holdable) &&
1019 isTrue($_->holdable) &&
1020 !isTrue($_->deleted)
1023 # let 'em know we're still working
1024 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1026 # if we have no copies ...
1027 if (!ref $all_copies || !@$all_copies) {
1028 $log->info("\tNo copies available for targeting at all!\n");
1029 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
1031 $hold->update( { prev_check_time => 'today', current_copy => undef } );
1032 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1036 my $copy_count = @$all_copies;
1038 # map the potentials, so that we can pick up checkins
1039 # XXX Loop-based targeting may require that /only/ copies from this loop should be added to
1040 # XXX the potentials list. If this is the cased, hold_copy_map creation will move down further.
1041 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
1042 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
1044 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1047 for my $c (@$all_copies) {
1049 next if ($c->id eq $hold->current_copy);
1051 # circ lib is closed
1052 next if ( grep { ''.$_->org_unit eq ''.$c->circ_lib } @closed );
1054 # target of another hold
1055 next if (action::hold_request
1057 { current_copy => $c->id,
1058 fulfillment_time => undef,
1059 cancel_time => undef,
1064 # we passed all three, keep it
1065 push @good_copies, $c if ($c);
1066 #$client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1069 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
1071 my $old_best = $hold->current_copy;
1072 $hold->update({ current_copy => undef }) if ($old_best);
1074 if (!scalar(@good_copies)) {
1075 $log->info("\tNo (non-current) copies eligible to fill the hold.");
1076 if ( $old_best && grep { ''.$old_best->id eq ''.$_->id } @$all_copies ) {
1077 # the old copy is still available
1078 $log->debug("\tPushing current_copy back onto the targeting list");
1079 push @good_copies, $old_best;
1081 # oops, old copy is not available
1082 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
1083 $hold->update( { prev_check_time => 'today' } );
1084 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1085 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
1094 $_->circ_lib == $hold->pickup_lib
1098 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1099 # $all_copies is now a list of copies not at the pickup library
1101 my $best = choose_nearest_copy($hold, $prox_list);
1102 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1105 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
1107 my $max_loops = $actor->request(
1108 'open-ils.actor.ou_setting.ancestor_default' => $hold->pickup_lib => 'circ.holds.max_org_unit_target_loops'
1111 if (defined($max_loops)) {
1112 my %circ_lib_map = map { $_->circ_lib => 1 } @$all_copies;
1113 my $circ_lib_list = [keys %circ_lib_map];
1115 my $cstore = OpenSRF::AppSession->connect('open-ils.cstore');
1117 # Grab the "biggest" loop for this hold so far
1118 my $current_loop = $cstore->request(
1119 'open-ils.cstore.json_query',
1121 select => { aufhmxl => ['max'] },
1123 where => { hold => $hold->id}
1127 $current_loop = $current_loop->{max} if ($current_loop);
1128 $current_loop ||= 1;
1130 my $exclude_list = $cstore->request(
1131 'open-ils.cstore.json_query.atomic',
1133 select => { aufhol => [circ_lib] },
1135 where => { hold => $hold->id}
1140 if ($exclude_list && @$exclude_list) {
1141 $exclude_list = [map {$_->{circ_lib}} @$exclude_list];
1142 # check to see if we've used up every library in the potentials list
1143 for my $l ( @$circ_lib_list ) {
1145 for my $ex ( @$exclude_list ) {
1151 push(@keepers, $l) if ($keep);
1154 @keepers = @$circ_lib_list;
1157 $current_loop++ if (!@keepers);
1159 if ($max_loops && $max_loops <= $current_loop) {
1160 # We haven't exceeded max_loops yet
1162 for my $cp ( @$all_copies ) {
1163 push (@keeper_copies, $cp) if ( grep { $_ eq $cp->circ_lib } @keepers );
1166 # We have, and should remove potentials and cancel the hold
1167 my @oldmaps = action::hold_copy_map->search( hold => $hold->id );
1168 $_->delete for (@oldmaps);
1170 # cancel cause = un-targeted expiration
1171 $hold->update( { cancel_time => 'now', cancel_cause => 1 } );
1172 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1174 # tell A/T the hold was cancelled
1175 my $fm_hold = $hold->to_fieldmapper;
1176 my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1177 $ses->request('open-ils.trigger.event.autocreate',
1178 'hold_request.cancel.expire_no_target', $fm_hold, $fm_hold->pickup_lib);
1184 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
1186 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1188 $best = choose_nearest_copy($hold, $prox_list);
1191 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
1193 # hold wasn't fulfilled, record the fact
1195 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
1196 action::unfulfilled_hold_list->create(
1197 { hold => ''.$hold->id,
1198 current_copy => ''.$old_best->id,
1199 circ_lib => ''.$old_best->circ_lib,
1204 $hold->update( { current_copy => ''.$best->id, prev_check_time => 'now' } );
1205 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
1208 action::hold_request
1210 { current_copy => $old_best->id,
1211 fulfillment_time => undef,
1212 cancel_time => undef,
1216 $hold->update( { prev_check_time => 'now', current_copy => ''.$old_best->id } );
1217 $log->debug( "\tRetargeting the previously targeted copy [".$old_best->id."]" );
1219 $hold->update( { prev_check_time => 'now' } );
1220 $log->info( "\tThere were no targetable copies for the hold" );
1223 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1224 $log->info("\tProcessing of hold ".$hold->id." complete.");
1227 { hold => $hold->id,
1228 old_target => ($old_best ? $old_best->id : undef),
1229 eligible_copies => $copy_count,
1230 target => ($best ? $best->id : undef) };
1235 $log->error("Processing of hold failed: $e");
1236 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1237 throw $e if ($e =~ /IS NOT CONNECTED TO THE NETWORK/o);
1244 __PACKAGE__->register_method(
1245 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1247 method => 'new_hold_copy_targeter',
1252 my %cache = (titles => {}, cns => {});
1253 sub hold_copy_targeter {
1256 my $check_expire = shift;
1257 my $one_hold = shift;
1259 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
1260 $self->{user_filter}->connect;
1261 $self->{client} = $client;
1264 $check_expire ||= '12h';
1265 $check_expire = interval_to_seconds( $check_expire );
1267 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
1270 my $expire_threshold = sprintf(
1271 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1272 $year, $mon, $mday, $hour, $min, $sec
1276 $statuses ||= [ config::copy_status->search(holdable => 't') ];
1278 $locations ||= [ asset::copy_location->search(holdable => 't') ];
1282 %cache = (titles => {}, cns => {});
1286 $holds = [ action::hold_request->search(id => $one_hold) ];
1288 $holds = [ action::hold_request->search_where(
1289 { capture_time => undef,
1290 prev_check_time => { '<=' => $expire_threshold },
1292 { order_by => 'request_time,prev_check_time' } ) ];
1293 push @$holds, action::hold_request->search_where(
1294 { capture_time => undef,
1295 prev_check_time => undef,
1297 { order_by => 'request_time' } );
1299 } catch Error with {
1301 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
1304 for my $hold (@$holds) {
1306 #action::hold_request->db_Main->begin_work;
1307 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
1308 $client->respond("Cleaning up after previous transaction\n");
1309 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1311 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
1312 $client->respond("Processing hold ".$hold->id."...\n");
1316 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
1317 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1319 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
1320 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1322 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
1323 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1325 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
1327 unless (ref $copies || !@$copies) {
1328 $client->respond("\tNo copies available for targeting at all!\n");
1332 for my $c (@$copies) {
1333 next if ( grep {$c->id == $hold->current_copy} @good_copies);
1334 push @good_copies, $c if ($c);
1337 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
1339 my $old_best = $hold->current_copy;
1340 $hold->update({ current_copy => undef });
1342 if (!scalar(@good_copies)) {
1343 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
1344 if ( $old_best && grep {$_->id == $hold->current_copy} @$copies ) {
1345 $client->respond("\tPushing current_copy back onto the targeting list\n");
1346 push @good_copies, asset::copy->retrieve( $old_best );
1348 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
1354 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
1355 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
1357 my $best = choose_nearest_copy($hold, $prox_list);
1360 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
1361 $best = choose_nearest_copy($hold, $prox_list);
1365 # hold wasn't fulfilled, record the fact
1367 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
1368 action::unfulfilled_hold_list->create(
1369 { hold => ''.$hold->id,
1370 current_copy => ''.$old_best->id,
1371 circ_lib => ''.$old_best->circ_lib,
1376 $hold->update( { current_copy => ''.$best->id } );
1377 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
1380 $hold->update( { prev_check_time => 'now' } );
1381 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
1383 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
1384 $self->method_lookup('open-ils.storage.transaction.commit')->run;
1386 #action::hold_request->dbi_commit;
1390 $log->error("Processing of hold failed: $e");
1391 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
1392 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
1393 #action::hold_request->dbi_rollback;
1397 $self->{user_filter}->disconnect;
1398 $self->{user_filter}->finish;
1399 delete $$self{user_filter};
1402 #__PACKAGE__->register_method(
1403 # api_name => 'open-ils.storage.action.hold_request.copy_targeter',
1406 # method => 'hold_copy_targeter',
1410 sub copy_hold_capture {
1415 if (!defined($cps)) {
1417 $cps = [ asset::copy->search( id => $hold->target ) ];
1418 } catch Error with {
1420 die "Could not retrieve initial volume list:\n\n$e\n";
1424 my @copies = grep { $_->holdable } @$cps;
1426 for (my $i = 0; $i < @$cps; $i++) {
1427 next unless $$cps[$i];
1429 my $cn = $cache{cns}{$copies[$i]->call_number};
1430 my $rec = $cache{titles}{$cn->record};
1431 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1432 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1433 $copies[$i] = undef if (
1435 !$self->{user_filter}->request(
1436 'open-ils.circ.permit_hold',
1437 $hold->to_fieldmapper, do {
1438 my $cp_fm = $copies[$i]->to_fieldmapper;
1439 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1440 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1441 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1444 { title => $rec->to_fieldmapper,
1445 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1446 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1449 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1452 @copies = grep { $_ } @copies;
1454 my $count = @copies;
1456 return unless ($count);
1458 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1461 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1462 for my $c (@copies) {
1463 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1465 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1471 sub choose_nearest_copy {
1473 my $prox_list = shift;
1475 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1476 next unless (ref $$prox_list[$p]);
1478 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1479 next unless (@capturable);
1481 my $rand = int(rand(scalar(@capturable)));
1482 while (my ($c) = splice(@capturable,$rand)) {
1483 return $c if ( OpenILS::Utils::PermitHold::permit_copy_hold(
1484 { title => $c->call_number->record->to_fieldmapper,
1485 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1486 patron => $hold->usr->to_fieldmapper,
1487 copy => $c->to_fieldmapper,
1488 requestor => $hold->requestor->to_fieldmapper,
1489 request_lib => $hold->request_lib->to_fieldmapper,
1490 pickup_lib => $hold->pickup_lib->id,
1494 last unless(@capturable);
1495 $rand = int(rand(scalar(@capturable)));
1500 sub create_prox_list {
1505 my $actor = OpenSRF::AppSession->create('open-ils.actor');
1508 for my $cp (@$copies) {
1509 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1510 next unless (defined($prox));
1512 # Fetch the weighting value for hold targeting, defaulting to 1
1513 $self->{target_weight} ||= $actor->request(
1514 'open-ils.actor.ou_setting.ancestor_default' => $lib => 'circ.holds.org_unit_target_weight'
1517 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1518 for my $w ( 1 .. $self->{target_weight} ) {
1519 push @{$prox_list[$prox]}, $cp;
1525 sub volume_hold_capture {
1530 if (!defined($vols)) {
1532 $vols = [ asset::call_number->search( id => $hold->target ) ];
1533 $cache{cns}{$_->id} = $_ for (@$vols);
1534 } catch Error with {
1536 die "Could not retrieve initial volume list:\n\n$e\n";
1540 my @v_ids = map { $_->id } @$vols;
1544 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1546 } catch Error with {
1548 warn "Could not retrieve copy list:\n\n$e\n";
1551 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1554 sub title_hold_capture {
1559 if (!defined($titles)) {
1561 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1562 $cache{titles}{$_->id} = $_ for (@$titles);
1563 } catch Error with {
1565 die "Could not retrieve initial title list:\n\n$e\n";
1569 my @t_ids = map { $_->id } @$titles;
1572 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1574 } catch Error with {
1576 warn "Could not retrieve volume list:\n\n$e\n";
1579 $cache{cns}{$_->id} = $_ for (@$cn_list);
1581 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1584 sub metarecord_hold_capture {
1590 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1592 } catch Error with {
1594 die "Could not retrieve initial title list:\n\n$e\n";
1598 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1600 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1602 } catch Error with {
1604 die "Could not retrieve format-pruned title list:\n\n$e\n";
1608 $cache{titles}{$_->id} = $_ for (@$titles);
1609 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);