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;
13 my $parser = DateTime::Format::ISO8601->new;
14 my $log = 'OpenSRF::Utils::Logger';
16 sub open_noncat_circs {
21 my $a = action::non_cataloged_circulation->table;
22 my $c = config::non_cataloged_type->table;
27 JOIN $c c ON (a.item_type = c.id)
28 WHERE a.circ_time + c.circ_duration > current_timestamp
32 return action::non_cataloged_circulation->db_Main->selectcol_arrayref($sql, {}, $user);
34 __PACKAGE__->register_method(
35 api_name => 'open-ils.storage.action.open_non_cataloged_circulation.user',
38 method => 'open_noncat_circs',
42 sub ou_hold_requests {
47 my $h_table = action::hold_request->table;
48 my $c_table = asset::copy->table;
49 my $o_table = actor::org_unit->table;
54 JOIN $c_table cp ON (cp.id = h.current_copy)
55 JOIN $o_table ou ON (ou.id = cp.circ_lib)
57 AND h.capture_time IS NULL
58 AND h.cancel_time IS NULL
59 ORDER BY h.request_time
62 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
65 $client->respond($_) for (
68 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
72 } @{ $sth->fetchall_arrayref }
76 __PACKAGE__->register_method(
77 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
81 method => 'ou_hold_requests',
88 my $c_t = action::circulation->table;
90 $grace = " - ($grace * (fine_interval))" if ($grace);
95 WHERE stop_fines IS NULL
96 AND due_date < ( CURRENT_TIMESTAMP $grace)
99 my $sth = action::circulation->db_Main->prepare_cached($sql);
102 return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
106 sub complete_reshelving {
111 local $OpenILS::Application::Storage::WRITE = 1;
113 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
114 unless (interval_to_seconds( $window ));
116 my $circ = action::circulation->table;
117 my $cp = asset::copy->table;
122 WHERE id IN ( SELECT cp.id
124 JOIN $circ circ ON (circ.target_copy = cp.id)
125 WHERE circ.checkin_time IS NOT NULL
126 AND circ.checkin_time < NOW() - CAST(? AS INTERVAL)
130 my $sth = action::circulation->db_Main->prepare_cached($sql);
131 $sth->execute($window);
136 __PACKAGE__->register_method(
137 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
141 method => 'complete_reshelving',
147 my $grace = shift || '';
149 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
154 __PACKAGE__->register_method(
155 api_name => 'open-ils.storage.action.circulation.overdue',
158 method => 'grab_overdue',
166 my $limit = int(shift()) || 10;
168 my ($id) = action::hold_request->db_Main->selectrow_array(<<" SQL", {}, $cp, $pl);
170 FROM action.hold_request h
171 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
172 JOIN actor.org_unit_proximity p ON (p.from_org = h.pickup_lib)
173 WHERE hm.target_copy = ?
175 AND h.capture_time IS NULL
176 AND h.cancel_time IS NULL
179 h.selection_depth DESC,
185 __PACKAGE__->register_method(
186 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
189 method => 'nearest_hold',
192 sub next_resp_group_id {
196 # XXX This is not replication safe!!!
198 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
199 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
203 __PACKAGE__->register_method(
204 api_name => 'open-ils.storage.action.survey_response.next_group_id',
206 method => 'next_resp_group_id',
209 sub patron_circ_summary {
214 return undef unless ($id);
215 my $c_table = action::circulation->table;
216 my $b_table = money::billing->table;
218 $log->debug("Retrieving patron summary for id $id", DEBUG);
220 my $select = <<" SQL";
221 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
223 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
225 AND c.xact_finish IS NULL
227 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
228 OR c.stop_fines IS NULL
232 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
234 __PACKAGE__->register_method(
235 api_name => 'open-ils.storage.action.circulation.patron_summary',
237 method => 'patron_circ_summary',
240 #XXX Fix stored proc calls
241 sub find_local_surveys {
246 return undef unless ($ou);
247 my $s_table = action::survey->table;
249 my $select = <<" SQL";
252 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
253 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
256 my $sth = action::survey->db_Main->prepare_cached($select);
259 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
263 __PACKAGE__->register_method(
264 api_name => 'open-ils.storage.action.survey.all',
267 method => 'find_local_surveys',
270 #XXX Fix stored proc calls
271 sub find_opac_surveys {
276 return undef unless ($ou);
277 my $s_table = action::survey->table;
279 my $select = <<" SQL";
282 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
283 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
287 my $sth = action::survey->db_Main->prepare_cached($select);
290 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
294 __PACKAGE__->register_method(
295 api_name => 'open-ils.storage.action.survey.opac',
298 method => 'find_opac_surveys',
305 my $limit = shift || 10;
306 my $offset = shift || 0;
308 return undef unless ($ou);
309 my $h_table = action::hold_request->table;
310 my $a_table = asset::copy->table;
312 my $select = <<" SQL";
315 JOIN $a_table a ON (h.current_copy = a.id)
317 AND h.capture_time IS NULL
318 AND h.cancel_time IS NULL
319 ORDER BY h.request_time ASC
324 my $sth = action::survey->db_Main->prepare_cached($select);
327 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
331 __PACKAGE__->register_method(
332 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
336 "Returns the holds for a specific library's pull list.",
337 [ [org_unit => "The library's org id", "number"],
338 [limit => 'An optional page size, defaults to 10', 'number'],
339 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
341 ['A list of holds for the stated library to pull for', 'array']
343 method => 'hold_pull_list',
346 sub find_optional_surveys {
351 return undef unless ($ou);
352 my $s_table = action::survey->table;
354 my $select = <<" SQL";
357 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
358 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
359 AND s.required IS FALSE;
362 my $sth = action::survey->db_Main->prepare_cached($select);
365 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
369 __PACKAGE__->register_method(
370 api_name => 'open-ils.storage.action.survey.optional',
373 method => 'find_optional_surveys',
376 sub find_required_surveys {
381 return undef unless ($ou);
382 my $s_table = action::survey->table;
384 my $select = <<" SQL";
387 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
388 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
389 AND s.required IS TRUE;
392 my $sth = action::survey->db_Main->prepare_cached($select);
395 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
399 __PACKAGE__->register_method(
400 api_name => 'open-ils.storage.action.survey.required',
403 method => 'find_required_surveys',
406 sub find_usr_summary_surveys {
411 return undef unless ($ou);
412 my $s_table = action::survey->table;
414 my $select = <<" SQL";
417 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
418 WHERE CURRENT_TIMESTAMP BETWEEN s.start_date AND s.end_date
419 AND s.usr_summary IS TRUE;
422 my $sth = action::survey->db_Main->prepare_cached($select);
425 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
429 __PACKAGE__->register_method(
430 api_name => 'open-ils.storage.action.survey.usr_summary',
433 method => 'find_usr_summary_surveys',
443 local $OpenILS::Application::Storage::WRITE = 1;
447 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
449 push @circs, overdue_circs($grace);
452 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
456 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
458 my $due = $due_dt->epoch;
460 my $fine_interval = interval_to_seconds( $c->fine_interval );
462 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
464 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
465 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
468 $due -= ($due % $fine_interval) + $tz_offset_s;
469 $now -= ($now % $fine_interval) + $tz_offset_s;
473 "ARG! Overdue circulation ".$c->id.
474 " for item ".$c->target_copy.
475 " (user ".$c->usr.").\n".
476 "\tItem was due on or before: ".localtime($due)."\n");
478 my ($fine) = money::billing->search(
479 xact => $c->id, voided => 'f',
480 { order_by => 'billing_ts DESC', limit => '1' }
485 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
486 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
490 # XXX There is some contention over this ... it basically makes the grace period "hard" (non-fining)
491 #$last_fine += $fine_interval * $grace;
494 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ) - 1;
495 if ($pending_fine_count < 1) {
496 $client->respond( "\tNo fines to create. " );
497 if ($grace && $now < $due + $fine_interval * $grace) {
498 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
500 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
505 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
507 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
509 my ($total) = money::billable_transaction_summary->retrieve( $c->id );
511 if ($total && $total->total_owed > $c->max_fine) {
512 $c->update({stop_fines => 'MAXFINES'});
514 "\tMaximum fine level of ".$c->max_fine.
515 " reached for this circulation.\n".
516 "\tNo more fines will be generated.\n" );
520 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
522 my $dow = $billing_ts->dow;
523 my $dow_open = "dow_${dow}_open";
524 my $dow_close = "dow_${dow}_close";
526 if (my $hoo = actor::org_unit::hours_of_operation->retrieve( $c->circ_lib )) {
527 next if ( $hoo->$dow_open eq '00:00:00' and $hoo->$dow_close eq '00:00:00');
530 my $timestamptz = $billing_ts->strftime('%FT%T%z');
531 my @cl = actor::org_unit::closed_date->search_where(
532 { close_start => { '<=' => $timestamptz },
533 close_end => { '>=' => $timestamptz },
534 org_unit => $c->circ_lib }
538 my $billing = money::billing->create(
540 note => "Overdue Fine",
541 billing_type => "Overdue materials",
542 amount => ''.$c->recuring_fine,
543 billing_ts => $timestamptz,
548 "\t\tCreating fine of ".$billing->amount." for period starting ".
550 $parser->parse_datetime(
551 clense_ISO8601( $billing->billing_ts )
557 'open-ils.penalty.patron_penalty.calculate',
558 { patron => $c->usr->to_fieldmapper,
566 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
570 __PACKAGE__->register_method(
571 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
574 method => 'generate_fines',
579 sub new_hold_copy_targeter {
582 my $check_expire = shift;
583 my $one_hold = shift;
585 local $OpenILS::Application::Storage::WRITE = 1;
591 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef, cancel_time => undef } ) ];
592 } elsif ( $check_expire ) {
595 $check_expire ||= '12h';
596 $check_expire = interval_to_seconds( $check_expire );
598 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
601 my $expire_threshold = sprintf(
602 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
603 $year, $mon, $mday, $hour, $min, $sec
606 $holds = [ action::hold_request->search_where(
607 { capture_time => undef,
608 fulfillment_time => undef,
609 cancel_time => undef,
610 prev_check_time => { '<=' => $expire_threshold },
612 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
613 push @$holds, action::hold_request->search(
614 capture_time => undef,
615 fulfillment_time => undef,
616 prev_check_time => undef,
617 cancel_time => undef,
618 { order_by => 'selection_depth DESC, request_time' } );
620 $holds = [ action::hold_request->search(
621 capture_time => undef,
622 fulfillment_time => undef,
623 prev_check_time => undef,
624 cancel_time => undef,
625 { order_by => 'selection_depth DESC, request_time' } ) ];
629 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
634 for my $hold (@$holds) {
636 #action::hold_request->db_Main->begin_work;
637 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
638 $log->debug("Cleaning up after previous transaction\n");
639 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
641 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
642 $log->info("Processing hold ".$hold->id."...\n");
644 action::hold_copy_map->search( hold => $hold->id )->delete_all;
648 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
650 # find all the potential copies
651 if ($hold->hold_type eq 'M') {
654 metabib::record_descriptor
656 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
657 ( $types ? (item_type => [split '', $types]) : () ),
658 ( $formats ? (item_form => [split '', $formats]) : () ),
659 ( $lang ? (item_lang => $lang) : () ),
663 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
664 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
666 for my $cn ( @{ $rtree->call_numbers } ) {
668 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
671 } elsif ($hold->hold_type eq 'T') {
673 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
674 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
677 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
681 for my $cn ( @{ $rtree->call_numbers } ) {
683 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
685 } elsif ($hold->hold_type eq 'V') {
687 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
688 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
691 asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
693 } elsif ($hold->hold_type eq 'C') {
695 $all_copies = [asset::copy->retrieve($hold->target)];
698 @$all_copies = grep { $_->status->holdable &&
699 $_->location->holdable &&
703 # let 'em know we're still working
704 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
706 if (!ref $all_copies || !@$all_copies) {
707 $log->info("\tNo copies available for targeting at all!\n");
708 $self->method_lookup('open-ils.storage.transaction.commit')->run;
709 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
713 my $copy_count = @$all_copies;
715 # map the potentials, so that we can pick up checkins
716 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
717 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
719 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
721 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
724 my $today= sprintf( '%s-%0.2d-%0.2d', $year, $mon, $mday );
726 my @closed = actor::org_unit::closed_date->search_where(
727 { close_start => { '<=', $today },
728 close_end => { '>=', $today } }
732 for my $c (@$all_copies) {
733 next if ($c->id == $hold->current_copy);
734 next if ( grep { ''.$_->org_unit == ''.$c->circ_lib } @closed );
735 next if (action::hold_request
737 { current_copy => $c->id,
738 capture_time => undef,
739 cancel_time => undef,
743 push @good_copies, $c if ($c);
744 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
747 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
749 my $old_best = $hold->current_copy;
750 $hold->update({ current_copy => undef });
752 if (!scalar(@good_copies)) {
753 $log->info("\tNo (non-current) copies eligible to fill the hold.");
756 grep { $old_best eq $_ } @$all_copies &&
757 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef, cancel_time => undef })
759 $log->debug("\tPushing current_copy back onto the targeting list");
760 push @good_copies, $old_best;
762 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
763 $self->method_lookup('open-ils.storage.transaction.commit')->run;
764 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
769 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
774 $_->circ_lib == $hold->pickup_lib
778 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
780 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
781 my $best = choose_nearest_copy($hold, $prox_list);
782 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
785 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
786 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
788 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
790 $best = choose_nearest_copy($hold, $prox_list);
793 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
795 # hold wasn't fulfilled, record the fact
797 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
798 action::unfulfilled_hold_list->create(
799 { hold => ''.$hold->id,
800 current_copy => ''.$old_best->id,
801 circ_lib => ''.$old_best->circ_lib,
806 $hold->update( { current_copy => ''.$best->id } );
807 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
809 $log->info( "\tThere were no targetable copies for the hold" );
812 $hold->update( { prev_check_time => 'now' } );
814 $self->method_lookup('open-ils.storage.transaction.commit')->run;
815 $log->info("\tProcessing of hold ".$hold->id." complete.");
819 old_target => ($old_best ? $old_best->id : undef),
820 eligible_copies => $copy_count,
821 target => ($best ? $best->id : undef) };
826 $log->error("Processing of hold failed: $e");
827 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
834 __PACKAGE__->register_method(
835 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
837 method => 'new_hold_copy_targeter',
842 my %cache = (titles => {}, cns => {});
843 sub hold_copy_targeter {
846 my $check_expire = shift;
847 my $one_hold = shift;
849 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
850 $self->{user_filter}->connect;
851 $self->{client} = $client;
854 $check_expire ||= '12h';
855 $check_expire = interval_to_seconds( $check_expire );
857 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
860 my $expire_threshold = sprintf(
861 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
862 $year, $mon, $mday, $hour, $min, $sec
866 $statuses ||= [ config::copy_status->search(holdable => 't') ];
868 $locations ||= [ asset::copy_location->search(holdable => 't') ];
872 %cache = (titles => {}, cns => {});
876 $holds = [ action::hold_request->search(id => $one_hold) ];
878 $holds = [ action::hold_request->search_where(
879 { capture_time => undef,
880 prev_check_time => { '<=' => $expire_threshold },
882 { order_by => 'request_time,prev_check_time' } ) ];
883 push @$holds, action::hold_request->search_where(
884 { capture_time => undef,
885 prev_check_time => undef,
887 { order_by => 'request_time' } );
891 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
894 for my $hold (@$holds) {
896 #action::hold_request->db_Main->begin_work;
897 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
898 $client->respond("Cleaning up after previous transaction\n");
899 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
901 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
902 $client->respond("Processing hold ".$hold->id."...\n");
906 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
907 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
909 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
910 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
912 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
913 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
915 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
917 unless (ref $copies || !@$copies) {
918 $client->respond("\tNo copies available for targeting at all!\n");
922 for my $c (@$copies) {
923 next if ( grep {$c->id == $hold->current_copy} @good_copies);
924 push @good_copies, $c if ($c);
927 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
929 my $old_best = $hold->current_copy;
930 $hold->update({ current_copy => undef });
932 if (!scalar(@good_copies)) {
933 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
934 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
935 $client->respond("\tPushing current_copy back onto the targeting list\n");
936 push @good_copies, asset::copy->retrieve( $old_best );
938 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
944 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
945 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
947 my $best = choose_nearest_copy($hold, $prox_list);
950 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
951 $best = choose_nearest_copy($hold, $prox_list);
955 # hold wasn't fulfilled, record the fact
957 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
958 action::unfulfilled_hold_list->create(
959 { hold => ''.$hold->id,
960 current_copy => ''.$old_best->id,
961 circ_lib => ''.$old_best->circ_lib,
966 $hold->update( { current_copy => ''.$best->id } );
967 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
970 $hold->update( { prev_check_time => 'now' } );
971 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
973 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
974 $self->method_lookup('open-ils.storage.transaction.commit')->run;
976 #action::hold_request->dbi_commit;
980 $log->error("Processing of hold failed: $e");
981 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
982 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
983 #action::hold_request->dbi_rollback;
987 $self->{user_filter}->disconnect;
988 $self->{user_filter}->finish;
989 delete $$self{user_filter};
992 __PACKAGE__->register_method(
993 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
996 method => 'hold_copy_targeter',
1000 sub copy_hold_capture {
1005 if (!defined($cps)) {
1007 $cps = [ asset::copy->search( id => $hold->target ) ];
1008 } catch Error with {
1010 die "Could not retrieve initial volume list:\n\n$e\n";
1014 my @copies = grep { $_->holdable } @$cps;
1016 for (my $i = 0; $i < @$cps; $i++) {
1017 next unless $$cps[$i];
1019 my $cn = $cache{cns}{$copies[$i]->call_number};
1020 my $rec = $cache{titles}{$cn->record};
1021 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1022 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1023 $copies[$i] = undef if (
1025 !$self->{user_filter}->request(
1026 'open-ils.circ.permit_hold',
1027 $hold->to_fieldmapper, do {
1028 my $cp_fm = $copies[$i]->to_fieldmapper;
1029 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1030 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1031 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1034 { title => $rec->to_fieldmapper,
1035 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1036 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1039 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1042 @copies = grep { $_ } @copies;
1044 my $count = @copies;
1046 return unless ($count);
1048 action::hold_copy_map->search( hold => $hold->id )->delete_all;
1051 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1052 for my $c (@copies) {
1053 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1055 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1061 sub choose_nearest_copy {
1063 my $prox_list = shift;
1065 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1066 next unless (ref $$prox_list[$p]);
1068 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1069 next unless (@capturable);
1071 my $rand = int(rand(scalar(@capturable)));
1072 while (my ($c) = splice(@capturable,$rand)) {
1073 unless ( OpenILS::Utils::PermitHold::permit_copy_hold(
1074 { title => $c->call_number->record->to_fieldmapper,
1075 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1076 patron => $hold->usr->to_fieldmapper,
1077 copy => $c->to_fieldmapper,
1078 requestor => $hold->requestor->to_fieldmapper,
1079 request_lib => $hold->request_lib->to_fieldmapper,
1082 last unless(@capturable);
1083 $rand = int(rand(scalar(@capturable)));
1091 sub create_prox_list {
1097 for my $cp (@$copies) {
1098 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1099 next unless (defined($prox));
1100 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1101 push @{$prox_list[$prox]}, $cp;
1106 sub volume_hold_capture {
1111 if (!defined($vols)) {
1113 $vols = [ asset::call_number->search( id => $hold->target ) ];
1114 $cache{cns}{$_->id} = $_ for (@$vols);
1115 } catch Error with {
1117 die "Could not retrieve initial volume list:\n\n$e\n";
1121 my @v_ids = map { $_->id } @$vols;
1125 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1127 } catch Error with {
1129 warn "Could not retrieve copy list:\n\n$e\n";
1132 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1135 sub title_hold_capture {
1140 if (!defined($titles)) {
1142 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1143 $cache{titles}{$_->id} = $_ for (@$titles);
1144 } catch Error with {
1146 die "Could not retrieve initial title list:\n\n$e\n";
1150 my @t_ids = map { $_->id } @$titles;
1153 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1155 } catch Error with {
1157 warn "Could not retrieve volume list:\n\n$e\n";
1160 $cache{cns}{$_->id} = $_ for (@$cn_list);
1162 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1165 sub metarecord_hold_capture {
1171 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1173 } catch Error with {
1175 die "Could not retrieve initial title list:\n\n$e\n";
1179 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1181 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1183 } catch Error with {
1185 die "Could not retrieve format-pruned title list:\n\n$e\n";
1189 $cache{titles}{$_->id} = $_ for (@$titles);
1190 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);