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 .. $pending_fine_count) {
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 = money::billing->create(
513 note => "Overdue Fine",
514 billing_type => "Overdue materials",
515 amount => ''.$c->recuring_fine,
516 billing_ts => DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill )->strftime('%FT%T%z')
521 "\t\tCreating fine of ".$billing->amount." for period starting ".
523 $parser->parse_datetime(
524 clense_ISO8601( $billing->billing_ts )
530 'open-ils.penalty.patron_penalty.calculate',
531 { patron => $c->usr->to_fieldmapper,
539 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
543 __PACKAGE__->register_method(
544 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
547 method => 'generate_fines',
552 sub new_hold_copy_targeter {
555 my $check_expire = shift;
556 my $one_hold = shift;
558 local $OpenILS::Application::Storage::WRITE = 1;
564 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef } ) ];
565 } elsif ( $check_expire ) {
568 $check_expire ||= '12h';
569 $check_expire = interval_to_seconds( $check_expire );
571 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
574 my $expire_threshold = sprintf(
575 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
576 $year, $mon, $mday, $hour, $min, $sec
579 $holds = [ action::hold_request->search_where(
580 { capture_time => undef,
581 fulfillment_time => undef,
582 prev_check_time => { '<=' => $expire_threshold },
584 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
585 push @$holds, action::hold_request->search(
586 capture_time => undef,
587 fulfillment_time => undef,
588 prev_check_time => undef,
589 { order_by => 'selection_depth DESC, request_time' } );
591 $holds = [ action::hold_request->search(
592 capture_time => undef,
593 fulfillment_time => undef,
594 prev_check_time => undef,
595 { order_by => 'selection_depth DESC, request_time' } ) ];
599 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
604 for my $hold (@$holds) {
606 #action::hold_request->db_Main->begin_work;
607 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
608 $log->debug("Cleaning up after previous transaction\n");
609 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
611 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
612 $log->info("Processing hold ".$hold->id."...\n");
614 action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
618 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
620 # find all the potential copies
621 if ($hold->hold_type eq 'M') {
624 metabib::record_descriptor
626 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
627 ( $types ? (item_type => [split '', $types]) : () ),
628 ( $formats ? (item_form => [split '', $formats]) : () ),
629 ( $lang ? (item_lang => $lang) : () ),
633 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
634 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
636 for my $cn ( @{ $rtree->call_numbers } ) {
638 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
641 } elsif ($hold->hold_type eq 'T') {
643 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
644 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
647 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
651 for my $cn ( @{ $rtree->call_numbers } ) {
653 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
655 } elsif ($hold->hold_type eq 'V') {
657 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
658 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
661 asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
663 } elsif ($hold->hold_type eq 'C') {
665 $all_copies = [asset::copy->retrieve($hold->target)];
668 @$all_copies = grep { $_->status->holdable &&
669 $_->location->holdable &&
673 # let 'em know we're still working
674 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
676 if (!ref $all_copies || !@$all_copies) {
677 $log->info("\tNo copies available for targeting at all!\n");
678 $self->method_lookup('open-ils.storage.transaction.commit')->run;
679 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
684 for my $c ( @$all_copies ) {
686 if ( OpenILS::Utils::PermitHold::permit_copy_hold(
687 { title => $c->call_number->record->to_fieldmapper,
688 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
689 patron => $hold->usr->to_fieldmapper,
690 copy => $c->to_fieldmapper,
691 requestor => $hold->requestor->to_fieldmapper,
692 request_lib => $hold->request_lib->to_fieldmapper,
695 my $copy_count = @$copies;
696 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
698 # map the potentials, so that we can pick up checkins
699 $log->debug( "\tMapping ".scalar(@$copies)." potential copies for hold ".$hold->id);
700 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$copies);
703 for my $c (@$copies) {
704 next if ($c->id == $hold->current_copy);
705 next if (action::hold_request
707 { current_copy => $c->id,
708 capture_time => undef,
712 push @good_copies, $c if ($c);
715 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
717 my $old_best = $hold->current_copy;
718 $hold->update({ current_copy => undef });
720 if (!scalar(@good_copies)) {
721 $log->info("\tNo (non-current) copies eligible to fill the hold.");
724 grep { $old_best eq $_ } @$copies &&
725 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef })
727 $log->debug("\tPushing current_copy back onto the targeting list");
728 push @good_copies, $old_best;
730 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
731 $self->method_lookup('open-ils.storage.transaction.commit')->run;
732 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
737 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
742 $_->circ_lib == $hold->pickup_lib
746 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
748 my $best = choose_nearest_copy($hold, $prox_list);
751 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$copies)." copies");
752 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
753 $best = choose_nearest_copy($hold, $prox_list);
756 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
758 # hold wasn't fulfilled, record the fact
760 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
761 action::unfulfilled_hold_list->create(
762 { hold => ''.$hold->id,
763 current_copy => ''.$old_best->id,
764 circ_lib => ''.$old_best->circ_lib,
769 $hold->update( { current_copy => ''.$best->id } );
770 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
772 $log->info( "\tThere were no targetable copies for the hold" );
775 $hold->update( { prev_check_time => 'now' } );
777 $self->method_lookup('open-ils.storage.transaction.commit')->run;
778 $log->info("\tProcessing of hold ".$hold->id." complete.");
782 old_target => ($old_best ? $old_best->id : undef),
783 eligible_copies => $copy_count,
784 target => ($best ? $best->id : undef) };
789 $log->error("Processing of hold failed: $e");
790 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
797 __PACKAGE__->register_method(
798 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
800 method => 'new_hold_copy_targeter',
805 my %cache = (titles => {}, cns => {});
806 sub hold_copy_targeter {
809 my $check_expire = shift;
810 my $one_hold = shift;
812 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
813 $self->{user_filter}->connect;
814 $self->{client} = $client;
817 $check_expire ||= '12h';
818 $check_expire = interval_to_seconds( $check_expire );
820 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
823 my $expire_threshold = sprintf(
824 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
825 $year, $mon, $mday, $hour, $min, $sec
829 $statuses ||= [ config::copy_status->search(holdable => 't') ];
831 $locations ||= [ asset::copy_location->search(holdable => 't') ];
835 %cache = (titles => {}, cns => {});
839 $holds = [ action::hold_request->search(id => $one_hold) ];
841 $holds = [ action::hold_request->search_where(
842 { capture_time => undef,
843 prev_check_time => { '<=' => $expire_threshold },
845 { order_by => 'request_time,prev_check_time' } ) ];
846 push @$holds, action::hold_request->search(
847 capture_time => undef,
848 prev_check_time => undef,
849 { order_by => 'request_time' } );
853 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
856 for my $hold (@$holds) {
858 #action::hold_request->db_Main->begin_work;
859 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
860 $client->respond("Cleaning up after previous transaction\n");
861 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
863 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
864 $client->respond("Processing hold ".$hold->id."...\n");
868 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
869 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
871 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
872 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
874 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
875 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
877 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
879 unless (ref $copies || !@$copies) {
880 $client->respond("\tNo copies available for targeting at all!\n");
884 for my $c (@$copies) {
885 next if ( grep {$c->id == $hold->current_copy} @good_copies);
886 push @good_copies, $c if ($c);
889 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
891 my $old_best = $hold->current_copy;
892 $hold->update({ current_copy => undef });
894 if (!scalar(@good_copies)) {
895 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
896 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
897 $client->respond("\tPushing current_copy back onto the targeting list\n");
898 push @good_copies, asset::copy->retrieve( $old_best );
900 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
906 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
907 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
909 my $best = choose_nearest_copy($hold, $prox_list);
912 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
913 $best = choose_nearest_copy($hold, $prox_list);
917 # hold wasn't fulfilled, record the fact
919 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
920 action::unfulfilled_hold_list->create(
921 { hold => ''.$hold->id,
922 current_copy => ''.$old_best->id,
923 circ_lib => ''.$old_best->circ_lib,
928 $hold->update( { current_copy => ''.$best->id } );
929 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
932 $hold->update( { prev_check_time => 'now' } );
933 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
935 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
936 $self->method_lookup('open-ils.storage.transaction.commit')->run;
938 #action::hold_request->dbi_commit;
942 $log->error("Processing of hold failed: $e");
943 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
944 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
945 #action::hold_request->dbi_rollback;
949 $self->{user_filter}->disconnect;
950 $self->{user_filter}->finish;
951 delete $$self{user_filter};
954 __PACKAGE__->register_method(
955 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
958 method => 'hold_copy_targeter',
962 sub copy_hold_capture {
967 if (!defined($cps)) {
969 $cps = [ asset::copy->search( id => $hold->target ) ];
972 die "Could not retrieve initial volume list:\n\n$e\n";
976 my @copies = grep { $_->holdable } @$cps;
978 for (my $i = 0; $i < @$cps; $i++) {
979 next unless $$cps[$i];
981 my $cn = $cache{cns}{$copies[$i]->call_number};
982 my $rec = $cache{titles}{$cn->record};
983 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
984 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
985 $copies[$i] = undef if (
987 !$self->{user_filter}->request(
988 'open-ils.circ.permit_hold',
989 $hold->to_fieldmapper, do {
990 my $cp_fm = $copies[$i]->to_fieldmapper;
991 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
992 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
993 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
996 { title => $rec->to_fieldmapper,
997 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
998 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1001 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1004 @copies = grep { $_ } @copies;
1006 my $count = @copies;
1008 return unless ($count);
1010 action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
1013 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1014 for my $c (@copies) {
1015 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1017 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1023 sub choose_nearest_copy {
1025 my $prox_list = shift;
1027 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1028 next unless (ref $$prox_list[$p]);
1029 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1030 next unless (@capturable);
1031 return $capturable[rand(scalar(@capturable))];
1035 sub create_prox_list {
1041 for my $cp (@$copies) {
1042 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp->id, $lib );
1043 next unless (defined($prox));
1044 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1045 push @{$prox_list[$prox]}, $cp;
1050 sub volume_hold_capture {
1055 if (!defined($vols)) {
1057 $vols = [ asset::call_number->search( id => $hold->target ) ];
1058 $cache{cns}{$_->id} = $_ for (@$vols);
1059 } catch Error with {
1061 die "Could not retrieve initial volume list:\n\n$e\n";
1065 my @v_ids = map { $_->id } @$vols;
1069 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1071 } catch Error with {
1073 warn "Could not retrieve copy list:\n\n$e\n";
1076 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1079 sub title_hold_capture {
1084 if (!defined($titles)) {
1086 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1087 $cache{titles}{$_->id} = $_ for (@$titles);
1088 } catch Error with {
1090 die "Could not retrieve initial title list:\n\n$e\n";
1094 my @t_ids = map { $_->id } @$titles;
1097 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1099 } catch Error with {
1101 warn "Could not retrieve volume list:\n\n$e\n";
1104 $cache{cns}{$_->id} = $_ for (@$cn_list);
1106 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1109 sub metarecord_hold_capture {
1115 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1117 } catch Error with {
1119 die "Could not retrieve initial title list:\n\n$e\n";
1123 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1125 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1127 } catch Error with {
1129 die "Could not retrieve format-pruned title list:\n\n$e\n";
1133 $cache{titles}{$_->id} = $_ for (@$titles);
1134 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);