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 ORDER BY h.request_time
61 my $sth = action::hold_request->db_Main->prepare_cached($SQL);
64 $client->respond($_) for (
67 ->method_lookup('open-ils.storage.direct.action.hold_request.retrieve')
71 } @{ $sth->fetchall_arrayref }
75 __PACKAGE__->register_method(
76 api_name => 'open-ils.storage.action.targeted_hold_request.org_unit',
80 method => 'ou_hold_requests',
87 my $c_t = action::circulation->table;
89 $grace = " - ($grace * (fine_interval))" if ($grace);
94 WHERE stop_fines IS NULL
95 AND due_date < ( CURRENT_TIMESTAMP $grace)
98 my $sth = action::circulation->db_Main->prepare_cached($sql);
101 return ( map { action::circulation->construct($_) } $sth->fetchall_hash );
105 sub complete_reshelving {
110 local $OpenILS::Application::Storage::WRITE = 1;
112 throw OpenSRF::EX::InvalidArg ("I need an interval of more than 0 seconds!")
113 unless (interval_to_seconds( $window ));
115 my $circ = action::circulation->table;
116 my $cp = asset::copy->table;
121 WHERE id IN ( SELECT cp.id
123 JOIN $circ circ ON (circ.target_copy = cp.id)
124 WHERE circ.checkin_time IS NOT NULL
125 AND circ.checkin_time < NOW() - CAST(? AS INTERVAL)
129 my $sth = action::circulation->db_Main->prepare_cached($sql);
130 $sth->execute($window);
135 __PACKAGE__->register_method(
136 api_name => 'open-ils.storage.action.circulation.reshelving.complete',
140 method => 'complete_reshelving',
146 my $grace = shift || '';
148 $client->respond( $_->to_fieldmapper ) for ( overdue_circs($grace) );
153 __PACKAGE__->register_method(
154 api_name => 'open-ils.storage.action.circulation.overdue',
157 method => 'grab_overdue',
166 my ($id) = action::hold_request->db_Main->selectrow_array(<<" SQL", {}, $pl,$cp);
168 FROM action.hold_request h
169 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
170 WHERE h.pickup_lib = ?
171 AND hm.target_copy = ?
172 AND h.capture_time IS NULL
173 ORDER BY h.pickup_lib - (SELECT home_ou FROM actor.usr a WHERE a.id = h.usr), h.selection_depth DESC, h.request_time
178 __PACKAGE__->register_method(
179 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
181 method => 'nearest_hold',
184 sub next_resp_group_id {
188 # XXX This is not replication safe!!!
190 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
191 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
195 __PACKAGE__->register_method(
196 api_name => 'open-ils.storage.action.survey_response.next_group_id',
198 method => 'next_resp_group_id',
201 sub patron_circ_summary {
206 return undef unless ($id);
207 my $c_table = action::circulation->table;
208 my $b_table = money::billing->table;
210 $log->debug("Retrieving patron summary for id $id", DEBUG);
212 my $select = <<" SQL";
213 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
215 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
217 AND c.xact_finish IS NULL
219 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
220 OR c.stop_fines IS NULL
224 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
226 __PACKAGE__->register_method(
227 api_name => 'open-ils.storage.action.circulation.patron_summary',
229 method => 'patron_circ_summary',
232 #XXX Fix stored proc calls
233 sub find_local_surveys {
238 return undef unless ($ou);
239 my $s_table = action::survey->table;
241 my $select = <<" SQL";
244 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
245 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
248 my $sth = action::survey->db_Main->prepare_cached($select);
251 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
255 __PACKAGE__->register_method(
256 api_name => 'open-ils.storage.action.survey.all',
259 method => 'find_local_surveys',
262 #XXX Fix stored proc calls
263 sub find_opac_surveys {
268 return undef unless ($ou);
269 my $s_table = action::survey->table;
271 my $select = <<" SQL";
274 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
275 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
279 my $sth = action::survey->db_Main->prepare_cached($select);
282 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
286 __PACKAGE__->register_method(
287 api_name => 'open-ils.storage.action.survey.opac',
290 method => 'find_opac_surveys',
297 my $limit = shift || 10;
298 my $offset = shift || 0;
300 return undef unless ($ou);
301 my $h_table = action::hold_request->table;
302 my $a_table = asset::copy->table;
304 my $select = <<" SQL";
307 JOIN $a_table a ON (h.current_copy = a.id)
309 AND h.capture_time IS NULL
310 ORDER BY h.request_time ASC
315 my $sth = action::survey->db_Main->prepare_cached($select);
318 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
322 __PACKAGE__->register_method(
323 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
327 "Returns the holds for a specific library's pull list.",
328 [ [org_unit => "The library's org id", "number"],
329 [limit => 'An optional page size, defaults to 10', 'number'],
330 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
332 ['A list of holds for the stated library to pull for', 'array']
334 method => 'hold_pull_list',
337 sub find_optional_surveys {
342 return undef unless ($ou);
343 my $s_table = action::survey->table;
345 my $select = <<" SQL";
348 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
349 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
350 AND s.required IS FALSE;
353 my $sth = action::survey->db_Main->prepare_cached($select);
356 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
360 __PACKAGE__->register_method(
361 api_name => 'open-ils.storage.action.survey.optional',
364 method => 'find_optional_surveys',
367 sub find_required_surveys {
372 return undef unless ($ou);
373 my $s_table = action::survey->table;
375 my $select = <<" SQL";
378 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
379 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
380 AND s.required IS TRUE;
383 my $sth = action::survey->db_Main->prepare_cached($select);
386 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
390 __PACKAGE__->register_method(
391 api_name => 'open-ils.storage.action.survey.required',
394 method => 'find_required_surveys',
397 sub find_usr_summary_surveys {
402 return undef unless ($ou);
403 my $s_table = action::survey->table;
405 my $select = <<" SQL";
408 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
409 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
410 AND s.usr_summary IS TRUE;
413 my $sth = action::survey->db_Main->prepare_cached($select);
416 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
420 __PACKAGE__->register_method(
421 api_name => 'open-ils.storage.action.survey.usr_summary',
424 method => 'find_usr_summary_surveys',
434 local $OpenILS::Application::Storage::WRITE = 1;
438 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
440 push @circs, overdue_circs($grace);
443 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
447 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
449 my $due = $due_dt->epoch;
451 my $fine_interval = interval_to_seconds( $c->fine_interval );
453 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
455 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
456 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
459 $due -= ($due % $fine_interval) + $tz_offset_s;
460 $now -= ($now % $fine_interval) + $tz_offset_s;
464 "ARG! Overdue circulation ".$c->id.
465 " for item ".$c->target_copy.
466 " (user ".$c->usr.").\n".
467 "\tItem was due on or before: ".localtime($due)."\n");
469 my ($fine) = money::billing->search(
470 xact => $c->id, voided => 'f',
471 { order_by => 'billing_ts DESC', limit => '1' }
476 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
477 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
481 # XXX There is some contention over this ... it basically makes the grace period "hard" (non-fining)
482 #$last_fine += $fine_interval * $grace;
485 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ) - 1;
486 if ($pending_fine_count < 1) {
487 $client->respond( "\tNo fines to create. " );
488 if ($grace && $now < $due + $fine_interval * $grace) {
489 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
491 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
496 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
498 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
500 my ($total) = money::billable_transaction_summary->retrieve( $c->id );
502 if ($total && $total->balance_owed > $c->max_fine) {
503 $c->update({stop_fines => 'MAXFINES'});
505 "\tMaximum fine level of ".$c->max_fine.
506 " reached for this circulation.\n".
507 "\tNo more fines will be generated.\n" );
511 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
513 my $dow = $billing_ts->dow;
514 my $dow_open = "dow_${dow}_open";
515 my $dow_close = "dow_${dow}_close";
517 my $hoo = actor::org_unit::hours_of_operation->retrieve( $c->circ_lib );
518 next if ( $hoo->$dow_open eq '00:00:00' and $hoo->$dow_close eq '00:00:00');
520 my $timestamptz = $billing_ts->strftime('%FT%T%z');
521 my @cl = actor::org_unit::closed_date->search_where(
522 { close_start => { '<=' => $timestamptz },
523 close_end => { '>=' => $timestamptz },
524 org_unit => $c->circ_lib }
528 my $billing = money::billing->create(
530 note => "Overdue Fine",
531 billing_type => "Overdue materials",
532 amount => ''.$c->recuring_fine,
533 billing_ts => $timestamptz,
538 "\t\tCreating fine of ".$billing->amount." for period starting ".
540 $parser->parse_datetime(
541 clense_ISO8601( $billing->billing_ts )
547 'open-ils.penalty.patron_penalty.calculate',
548 { patron => $c->usr->to_fieldmapper,
556 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
560 __PACKAGE__->register_method(
561 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
564 method => 'generate_fines',
569 sub new_hold_copy_targeter {
572 my $check_expire = shift;
573 my $one_hold = shift;
575 local $OpenILS::Application::Storage::WRITE = 1;
581 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef } ) ];
582 } elsif ( $check_expire ) {
585 $check_expire ||= '12h';
586 $check_expire = interval_to_seconds( $check_expire );
588 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
591 my $expire_threshold = sprintf(
592 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
593 $year, $mon, $mday, $hour, $min, $sec
596 $holds = [ action::hold_request->search_where(
597 { capture_time => undef,
598 fulfillment_time => undef,
599 prev_check_time => { '<=' => $expire_threshold },
601 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
602 push @$holds, action::hold_request->search(
603 capture_time => undef,
604 fulfillment_time => undef,
605 prev_check_time => undef,
606 { order_by => 'selection_depth DESC, request_time' } );
608 $holds = [ action::hold_request->search(
609 capture_time => undef,
610 fulfillment_time => undef,
611 prev_check_time => undef,
612 { order_by => 'selection_depth DESC, request_time' } ) ];
616 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
621 for my $hold (@$holds) {
623 #action::hold_request->db_Main->begin_work;
624 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
625 $log->debug("Cleaning up after previous transaction\n");
626 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
628 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
629 $log->info("Processing hold ".$hold->id."...\n");
631 action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
635 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
637 # find all the potential copies
638 if ($hold->hold_type eq 'M') {
641 metabib::record_descriptor
643 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
644 ( $types ? (item_type => [split '', $types]) : () ),
645 ( $formats ? (item_form => [split '', $formats]) : () ),
646 ( $lang ? (item_lang => $lang) : () ),
650 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
651 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
653 for my $cn ( @{ $rtree->call_numbers } ) {
655 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
658 } elsif ($hold->hold_type eq 'T') {
660 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
661 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
664 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
668 for my $cn ( @{ $rtree->call_numbers } ) {
670 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
672 } elsif ($hold->hold_type eq 'V') {
674 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
675 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
678 asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
680 } elsif ($hold->hold_type eq 'C') {
682 $all_copies = [asset::copy->retrieve($hold->target)];
685 @$all_copies = grep { $_->status->holdable &&
686 $_->location->holdable &&
690 # let 'em know we're still working
691 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
693 if (!ref $all_copies || !@$all_copies) {
694 $log->info("\tNo copies available for targeting at all!\n");
695 $self->method_lookup('open-ils.storage.transaction.commit')->run;
696 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
700 my $copy_count = @$all_copies;
702 # map the potentials, so that we can pick up checkins
703 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
704 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
706 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
709 for my $c (@$all_copies) {
710 next if ($c->id == $hold->current_copy);
711 next if (action::hold_request
713 { current_copy => $c->id,
714 capture_time => undef,
718 push @good_copies, $c if ($c);
719 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
722 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
724 my $old_best = $hold->current_copy;
725 $hold->update({ current_copy => undef });
727 if (!scalar(@good_copies)) {
728 $log->info("\tNo (non-current) copies eligible to fill the hold.");
731 grep { $old_best eq $_ } @$all_copies &&
732 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef })
734 $log->debug("\tPushing current_copy back onto the targeting list");
735 push @good_copies, $old_best;
737 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
738 $self->method_lookup('open-ils.storage.transaction.commit')->run;
739 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
744 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
749 $_->circ_lib == $hold->pickup_lib
753 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
755 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
756 my $best = choose_nearest_copy($hold, $prox_list);
757 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
760 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
761 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
763 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
765 $best = choose_nearest_copy($hold, $prox_list);
768 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
770 # hold wasn't fulfilled, record the fact
772 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
773 action::unfulfilled_hold_list->create(
774 { hold => ''.$hold->id,
775 current_copy => ''.$old_best->id,
776 circ_lib => ''.$old_best->circ_lib,
781 $hold->update( { current_copy => ''.$best->id } );
782 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
784 $log->info( "\tThere were no targetable copies for the hold" );
787 $hold->update( { prev_check_time => 'now' } );
789 $self->method_lookup('open-ils.storage.transaction.commit')->run;
790 $log->info("\tProcessing of hold ".$hold->id." complete.");
794 old_target => ($old_best ? $old_best->id : undef),
795 eligible_copies => $copy_count,
796 target => ($best ? $best->id : undef) };
801 $log->error("Processing of hold failed: $e");
802 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
809 __PACKAGE__->register_method(
810 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
812 method => 'new_hold_copy_targeter',
817 my %cache = (titles => {}, cns => {});
818 sub hold_copy_targeter {
821 my $check_expire = shift;
822 my $one_hold = shift;
824 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
825 $self->{user_filter}->connect;
826 $self->{client} = $client;
829 $check_expire ||= '12h';
830 $check_expire = interval_to_seconds( $check_expire );
832 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
835 my $expire_threshold = sprintf(
836 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
837 $year, $mon, $mday, $hour, $min, $sec
841 $statuses ||= [ config::copy_status->search(holdable => 't') ];
843 $locations ||= [ asset::copy_location->search(holdable => 't') ];
847 %cache = (titles => {}, cns => {});
851 $holds = [ action::hold_request->search(id => $one_hold) ];
853 $holds = [ action::hold_request->search_where(
854 { capture_time => undef,
855 prev_check_time => { '<=' => $expire_threshold },
857 { order_by => 'request_time,prev_check_time' } ) ];
858 push @$holds, action::hold_request->search(
859 capture_time => undef,
860 prev_check_time => undef,
861 { order_by => 'request_time' } );
865 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
868 for my $hold (@$holds) {
870 #action::hold_request->db_Main->begin_work;
871 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
872 $client->respond("Cleaning up after previous transaction\n");
873 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
875 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
876 $client->respond("Processing hold ".$hold->id."...\n");
880 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
881 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
883 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
884 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
886 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
887 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
889 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
891 unless (ref $copies || !@$copies) {
892 $client->respond("\tNo copies available for targeting at all!\n");
896 for my $c (@$copies) {
897 next if ( grep {$c->id == $hold->current_copy} @good_copies);
898 push @good_copies, $c if ($c);
901 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
903 my $old_best = $hold->current_copy;
904 $hold->update({ current_copy => undef });
906 if (!scalar(@good_copies)) {
907 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
908 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
909 $client->respond("\tPushing current_copy back onto the targeting list\n");
910 push @good_copies, asset::copy->retrieve( $old_best );
912 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
918 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
919 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
921 my $best = choose_nearest_copy($hold, $prox_list);
924 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
925 $best = choose_nearest_copy($hold, $prox_list);
929 # hold wasn't fulfilled, record the fact
931 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
932 action::unfulfilled_hold_list->create(
933 { hold => ''.$hold->id,
934 current_copy => ''.$old_best->id,
935 circ_lib => ''.$old_best->circ_lib,
940 $hold->update( { current_copy => ''.$best->id } );
941 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
944 $hold->update( { prev_check_time => 'now' } );
945 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
947 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
948 $self->method_lookup('open-ils.storage.transaction.commit')->run;
950 #action::hold_request->dbi_commit;
954 $log->error("Processing of hold failed: $e");
955 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
956 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
957 #action::hold_request->dbi_rollback;
961 $self->{user_filter}->disconnect;
962 $self->{user_filter}->finish;
963 delete $$self{user_filter};
966 __PACKAGE__->register_method(
967 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
970 method => 'hold_copy_targeter',
974 sub copy_hold_capture {
979 if (!defined($cps)) {
981 $cps = [ asset::copy->search( id => $hold->target ) ];
984 die "Could not retrieve initial volume list:\n\n$e\n";
988 my @copies = grep { $_->holdable } @$cps;
990 for (my $i = 0; $i < @$cps; $i++) {
991 next unless $$cps[$i];
993 my $cn = $cache{cns}{$copies[$i]->call_number};
994 my $rec = $cache{titles}{$cn->record};
995 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
996 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
997 $copies[$i] = undef if (
999 !$self->{user_filter}->request(
1000 'open-ils.circ.permit_hold',
1001 $hold->to_fieldmapper, do {
1002 my $cp_fm = $copies[$i]->to_fieldmapper;
1003 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1004 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1005 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1008 { title => $rec->to_fieldmapper,
1009 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1010 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1013 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1016 @copies = grep { $_ } @copies;
1018 my $count = @copies;
1020 return unless ($count);
1022 action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
1025 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1026 for my $c (@copies) {
1027 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1029 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1035 sub choose_nearest_copy {
1037 my $prox_list = shift;
1039 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1040 next unless (ref $$prox_list[$p]);
1042 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1043 next unless (@capturable);
1045 my $rand = int(rand(scalar(@capturable)));
1046 while (my ($c) = splice(@capturable,$rand)) {
1047 unless ( OpenILS::Utils::PermitHold::permit_copy_hold(
1048 { title => $c->call_number->record->to_fieldmapper,
1049 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1050 patron => $hold->usr->to_fieldmapper,
1051 copy => $c->to_fieldmapper,
1052 requestor => $hold->requestor->to_fieldmapper,
1053 request_lib => $hold->request_lib->to_fieldmapper,
1056 $rand = int(rand(scalar(@capturable)));
1064 sub create_prox_list {
1070 for my $cp (@$copies) {
1071 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp->id, $lib );
1072 next unless (defined($prox));
1073 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1074 push @{$prox_list[$prox]}, $cp;
1079 sub volume_hold_capture {
1084 if (!defined($vols)) {
1086 $vols = [ asset::call_number->search( id => $hold->target ) ];
1087 $cache{cns}{$_->id} = $_ for (@$vols);
1088 } catch Error with {
1090 die "Could not retrieve initial volume list:\n\n$e\n";
1094 my @v_ids = map { $_->id } @$vols;
1098 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1100 } catch Error with {
1102 warn "Could not retrieve copy list:\n\n$e\n";
1105 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1108 sub title_hold_capture {
1113 if (!defined($titles)) {
1115 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1116 $cache{titles}{$_->id} = $_ for (@$titles);
1117 } catch Error with {
1119 die "Could not retrieve initial title list:\n\n$e\n";
1123 my @t_ids = map { $_->id } @$titles;
1126 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1128 } catch Error with {
1130 warn "Could not retrieve volume list:\n\n$e\n";
1133 $cache{cns}{$_->id} = $_ for (@$cn_list);
1135 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1138 sub metarecord_hold_capture {
1144 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1146 } catch Error with {
1148 die "Could not retrieve initial title list:\n\n$e\n";
1152 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1154 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1156 } catch Error with {
1158 die "Could not retrieve format-pruned title list:\n\n$e\n";
1162 $cache{titles}{$_->id} = $_ for (@$titles);
1163 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);