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',
165 my $limit = int(shift()) || 10;
167 my ($id) = action::hold_request->db_Main->selectrow_array(<<" SQL", {}, $cp, $pl);
169 FROM action.hold_request h
170 JOIN action.hold_copy_map hm ON (hm.hold = h.id)
171 WHERE hm.target_copy = ?
172 AND h.capture_time IS NULL
174 actor.org_unit_proximity(h.pickup_lib, ?),
175 h.selection_depth DESC,
181 __PACKAGE__->register_method(
182 api_name => 'open-ils.storage.action.hold_request.nearest_hold',
185 method => 'nearest_hold',
188 sub next_resp_group_id {
192 # XXX This is not replication safe!!!
194 my ($id) = action::survey->db_Main->selectrow_array(<<" SQL");
195 SELECT NEXTVAL('action.survey_response_group_id_seq'::TEXT)
199 __PACKAGE__->register_method(
200 api_name => 'open-ils.storage.action.survey_response.next_group_id',
202 method => 'next_resp_group_id',
205 sub patron_circ_summary {
210 return undef unless ($id);
211 my $c_table = action::circulation->table;
212 my $b_table = money::billing->table;
214 $log->debug("Retrieving patron summary for id $id", DEBUG);
216 my $select = <<" SQL";
217 SELECT COUNT(DISTINCT c.id), SUM( COALESCE(b.amount,0) )
219 LEFT OUTER JOIN $b_table b ON (c.id = b.xact AND b.voided = FALSE)
221 AND c.xact_finish IS NULL
223 c.stop_fines NOT IN ('CLAIMSRETURNED','LOST')
224 OR c.stop_fines IS NULL
228 return action::survey->db_Main->selectrow_arrayref($select, {}, $id);
230 __PACKAGE__->register_method(
231 api_name => 'open-ils.storage.action.circulation.patron_summary',
233 method => 'patron_circ_summary',
236 #XXX Fix stored proc calls
237 sub find_local_surveys {
242 return undef unless ($ou);
243 my $s_table = action::survey->table;
245 my $select = <<" SQL";
248 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
249 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
252 my $sth = action::survey->db_Main->prepare_cached($select);
255 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
259 __PACKAGE__->register_method(
260 api_name => 'open-ils.storage.action.survey.all',
263 method => 'find_local_surveys',
266 #XXX Fix stored proc calls
267 sub find_opac_surveys {
272 return undef unless ($ou);
273 my $s_table = action::survey->table;
275 my $select = <<" SQL";
278 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
279 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
283 my $sth = action::survey->db_Main->prepare_cached($select);
286 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
290 __PACKAGE__->register_method(
291 api_name => 'open-ils.storage.action.survey.opac',
294 method => 'find_opac_surveys',
301 my $limit = shift || 10;
302 my $offset = shift || 0;
304 return undef unless ($ou);
305 my $h_table = action::hold_request->table;
306 my $a_table = asset::copy->table;
308 my $select = <<" SQL";
311 JOIN $a_table a ON (h.current_copy = a.id)
313 AND h.capture_time IS NULL
314 ORDER BY h.request_time ASC
319 my $sth = action::survey->db_Main->prepare_cached($select);
322 $client->respond( $_->to_fieldmapper ) for ( map { action::hold_request->construct($_) } $sth->fetchall_hash );
326 __PACKAGE__->register_method(
327 api_name => 'open-ils.storage.direct.action.hold_request.pull_list.search.current_copy_circ_lib',
331 "Returns the holds for a specific library's pull list.",
332 [ [org_unit => "The library's org id", "number"],
333 [limit => 'An optional page size, defaults to 10', 'number'],
334 [offset => 'Offset for paging, defaults to 0, 0 based', 'number'],
336 ['A list of holds for the stated library to pull for', 'array']
338 method => 'hold_pull_list',
341 sub find_optional_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_DATE BETWEEN s.start_date AND s.end_date
354 AND s.required IS FALSE;
357 my $sth = action::survey->db_Main->prepare_cached($select);
360 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
364 __PACKAGE__->register_method(
365 api_name => 'open-ils.storage.action.survey.optional',
368 method => 'find_optional_surveys',
371 sub find_required_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_DATE BETWEEN s.start_date AND s.end_date
384 AND s.required IS TRUE;
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.required',
398 method => 'find_required_surveys',
401 sub find_usr_summary_surveys {
406 return undef unless ($ou);
407 my $s_table = action::survey->table;
409 my $select = <<" SQL";
412 JOIN actor.org_unit_full_path(?) p ON (p.id = s.owner)
413 WHERE CURRENT_DATE BETWEEN s.start_date AND s.end_date
414 AND s.usr_summary IS TRUE;
417 my $sth = action::survey->db_Main->prepare_cached($select);
420 $client->respond( $_->to_fieldmapper ) for ( map { action::survey->construct($_) } $sth->fetchall_hash );
424 __PACKAGE__->register_method(
425 api_name => 'open-ils.storage.action.survey.usr_summary',
428 method => 'find_usr_summary_surveys',
438 local $OpenILS::Application::Storage::WRITE = 1;
442 push @circs, action::circulation->search_where( { id => $circ, stop_fines => undef } );
444 push @circs, overdue_circs($grace);
447 my $penalty = OpenSRF::AppSession->create('open-ils.penalty');
451 my $due_dt = $parser->parse_datetime( clense_ISO8601( $c->due_date ) );
453 my $due = $due_dt->epoch;
455 my $fine_interval = interval_to_seconds( $c->fine_interval );
457 if ( interval_to_seconds( $c->fine_interval ) >= interval_to_seconds('1d') ) {
459 if ($due_dt->strftime('%z') =~ /(-|\+)(\d{2}):?(\d{2})/) {
460 $tz_offset_s = $1 . interval_to_seconds( "${2}h ${3}m");
463 $due -= ($due % $fine_interval) + $tz_offset_s;
464 $now -= ($now % $fine_interval) + $tz_offset_s;
468 "ARG! Overdue circulation ".$c->id.
469 " for item ".$c->target_copy.
470 " (user ".$c->usr.").\n".
471 "\tItem was due on or before: ".localtime($due)."\n");
473 my ($fine) = money::billing->search(
474 xact => $c->id, voided => 'f',
475 { order_by => 'billing_ts DESC', limit => '1' }
480 $client->respond( "Last billing time: ".$fine->billing_ts." (clensed fromat: ".clense_ISO8601( $fine->billing_ts ).")");
481 $last_fine = $parser->parse_datetime( clense_ISO8601( $fine->billing_ts ) )->epoch;
485 # XXX There is some contention over this ... it basically makes the grace period "hard" (non-fining)
486 #$last_fine += $fine_interval * $grace;
489 my $pending_fine_count = int( ($now - $last_fine) / $fine_interval ) - 1;
490 if ($pending_fine_count < 1) {
491 $client->respond( "\tNo fines to create. " );
492 if ($grace && $now < $due + $fine_interval * $grace) {
493 $client->respond( "Still inside grace period of: ". seconds_to_interval( $fine_interval * $grace)."\n" );
495 $client->respond( "Last fine generated for: ".localtime($last_fine)."\n" );
500 $client->respond( "\t$pending_fine_count pending fine(s)\n" );
502 for (my $bill = 1; $bill <= $pending_fine_count; $bill++) {
504 my ($total) = money::billable_transaction_summary->retrieve( $c->id );
506 if ($total && $total->balance_owed > $c->max_fine) {
507 $c->update({stop_fines => 'MAXFINES'});
509 "\tMaximum fine level of ".$c->max_fine.
510 " reached for this circulation.\n".
511 "\tNo more fines will be generated.\n" );
515 my $billing_ts = DateTime->from_epoch( epoch => $last_fine + $fine_interval * $bill );
517 my $dow = $billing_ts->dow;
518 my $dow_open = "dow_${dow}_open";
519 my $dow_close = "dow_${dow}_close";
521 my $hoo = actor::org_unit::hours_of_operation->retrieve( $c->circ_lib );
522 next if ( $hoo->$dow_open eq '00:00:00' and $hoo->$dow_close eq '00:00:00');
524 my $timestamptz = $billing_ts->strftime('%FT%T%z');
525 my @cl = actor::org_unit::closed_date->search_where(
526 { close_start => { '<=' => $timestamptz },
527 close_end => { '>=' => $timestamptz },
528 org_unit => $c->circ_lib }
532 my $billing = money::billing->create(
534 note => "Overdue Fine",
535 billing_type => "Overdue materials",
536 amount => ''.$c->recuring_fine,
537 billing_ts => $timestamptz,
542 "\t\tCreating fine of ".$billing->amount." for period starting ".
544 $parser->parse_datetime(
545 clense_ISO8601( $billing->billing_ts )
551 'open-ils.penalty.patron_penalty.calculate',
552 { patron => $c->usr->to_fieldmapper,
560 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
564 __PACKAGE__->register_method(
565 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
568 method => 'generate_fines',
573 sub new_hold_copy_targeter {
576 my $check_expire = shift;
577 my $one_hold = shift;
579 local $OpenILS::Application::Storage::WRITE = 1;
585 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef } ) ];
586 } elsif ( $check_expire ) {
589 $check_expire ||= '12h';
590 $check_expire = interval_to_seconds( $check_expire );
592 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
595 my $expire_threshold = sprintf(
596 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
597 $year, $mon, $mday, $hour, $min, $sec
600 $holds = [ action::hold_request->search_where(
601 { capture_time => undef,
602 fulfillment_time => undef,
603 prev_check_time => { '<=' => $expire_threshold },
605 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
606 push @$holds, action::hold_request->search(
607 capture_time => undef,
608 fulfillment_time => undef,
609 prev_check_time => undef,
610 { order_by => 'selection_depth DESC, request_time' } );
612 $holds = [ action::hold_request->search(
613 capture_time => undef,
614 fulfillment_time => undef,
615 prev_check_time => undef,
616 { order_by => 'selection_depth DESC, request_time' } ) ];
620 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
625 for my $hold (@$holds) {
627 #action::hold_request->db_Main->begin_work;
628 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
629 $log->debug("Cleaning up after previous transaction\n");
630 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
632 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
633 $log->info("Processing hold ".$hold->id."...\n");
635 action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
639 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
641 # find all the potential copies
642 if ($hold->hold_type eq 'M') {
645 metabib::record_descriptor
647 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
648 ( $types ? (item_type => [split '', $types]) : () ),
649 ( $formats ? (item_form => [split '', $formats]) : () ),
650 ( $lang ? (item_lang => $lang) : () ),
654 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
655 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
657 for my $cn ( @{ $rtree->call_numbers } ) {
659 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
662 } elsif ($hold->hold_type eq 'T') {
664 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
665 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
668 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
672 for my $cn ( @{ $rtree->call_numbers } ) {
674 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
676 } elsif ($hold->hold_type eq 'V') {
678 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
679 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
682 asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
684 } elsif ($hold->hold_type eq 'C') {
686 $all_copies = [asset::copy->retrieve($hold->target)];
689 @$all_copies = grep { $_->status->holdable &&
690 $_->location->holdable &&
694 # let 'em know we're still working
695 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
697 if (!ref $all_copies || !@$all_copies) {
698 $log->info("\tNo copies available for targeting at all!\n");
699 $self->method_lookup('open-ils.storage.transaction.commit')->run;
700 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
704 my $copy_count = @$all_copies;
706 # map the potentials, so that we can pick up checkins
707 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
708 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
710 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
713 for my $c (@$all_copies) {
714 next if ($c->id == $hold->current_copy);
715 next if (action::hold_request
717 { current_copy => $c->id,
718 capture_time => undef,
722 push @good_copies, $c if ($c);
723 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
726 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
728 my $old_best = $hold->current_copy;
729 $hold->update({ current_copy => undef });
731 if (!scalar(@good_copies)) {
732 $log->info("\tNo (non-current) copies eligible to fill the hold.");
735 grep { $old_best eq $_ } @$all_copies &&
736 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef })
738 $log->debug("\tPushing current_copy back onto the targeting list");
739 push @good_copies, $old_best;
741 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
742 $self->method_lookup('open-ils.storage.transaction.commit')->run;
743 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
748 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
753 $_->circ_lib == $hold->pickup_lib
757 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
759 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
760 my $best = choose_nearest_copy($hold, $prox_list);
761 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
764 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
765 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
767 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
769 $best = choose_nearest_copy($hold, $prox_list);
772 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
774 # hold wasn't fulfilled, record the fact
776 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
777 action::unfulfilled_hold_list->create(
778 { hold => ''.$hold->id,
779 current_copy => ''.$old_best->id,
780 circ_lib => ''.$old_best->circ_lib,
785 $hold->update( { current_copy => ''.$best->id } );
786 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
788 $log->info( "\tThere were no targetable copies for the hold" );
791 $hold->update( { prev_check_time => 'now' } );
793 $self->method_lookup('open-ils.storage.transaction.commit')->run;
794 $log->info("\tProcessing of hold ".$hold->id." complete.");
798 old_target => ($old_best ? $old_best->id : undef),
799 eligible_copies => $copy_count,
800 target => ($best ? $best->id : undef) };
805 $log->error("Processing of hold failed: $e");
806 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
813 __PACKAGE__->register_method(
814 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
816 method => 'new_hold_copy_targeter',
821 my %cache = (titles => {}, cns => {});
822 sub hold_copy_targeter {
825 my $check_expire = shift;
826 my $one_hold = shift;
828 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
829 $self->{user_filter}->connect;
830 $self->{client} = $client;
833 $check_expire ||= '12h';
834 $check_expire = interval_to_seconds( $check_expire );
836 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
839 my $expire_threshold = sprintf(
840 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
841 $year, $mon, $mday, $hour, $min, $sec
845 $statuses ||= [ config::copy_status->search(holdable => 't') ];
847 $locations ||= [ asset::copy_location->search(holdable => 't') ];
851 %cache = (titles => {}, cns => {});
855 $holds = [ action::hold_request->search(id => $one_hold) ];
857 $holds = [ action::hold_request->search_where(
858 { capture_time => undef,
859 prev_check_time => { '<=' => $expire_threshold },
861 { order_by => 'request_time,prev_check_time' } ) ];
862 push @$holds, action::hold_request->search(
863 capture_time => undef,
864 prev_check_time => undef,
865 { order_by => 'request_time' } );
869 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
872 for my $hold (@$holds) {
874 #action::hold_request->db_Main->begin_work;
875 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
876 $client->respond("Cleaning up after previous transaction\n");
877 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
879 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
880 $client->respond("Processing hold ".$hold->id."...\n");
884 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
885 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
887 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
888 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
890 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
891 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
893 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
895 unless (ref $copies || !@$copies) {
896 $client->respond("\tNo copies available for targeting at all!\n");
900 for my $c (@$copies) {
901 next if ( grep {$c->id == $hold->current_copy} @good_copies);
902 push @good_copies, $c if ($c);
905 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
907 my $old_best = $hold->current_copy;
908 $hold->update({ current_copy => undef });
910 if (!scalar(@good_copies)) {
911 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
912 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
913 $client->respond("\tPushing current_copy back onto the targeting list\n");
914 push @good_copies, asset::copy->retrieve( $old_best );
916 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
922 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
923 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
925 my $best = choose_nearest_copy($hold, $prox_list);
928 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
929 $best = choose_nearest_copy($hold, $prox_list);
933 # hold wasn't fulfilled, record the fact
935 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
936 action::unfulfilled_hold_list->create(
937 { hold => ''.$hold->id,
938 current_copy => ''.$old_best->id,
939 circ_lib => ''.$old_best->circ_lib,
944 $hold->update( { current_copy => ''.$best->id } );
945 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
948 $hold->update( { prev_check_time => 'now' } );
949 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
951 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
952 $self->method_lookup('open-ils.storage.transaction.commit')->run;
954 #action::hold_request->dbi_commit;
958 $log->error("Processing of hold failed: $e");
959 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
960 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
961 #action::hold_request->dbi_rollback;
965 $self->{user_filter}->disconnect;
966 $self->{user_filter}->finish;
967 delete $$self{user_filter};
970 __PACKAGE__->register_method(
971 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
974 method => 'hold_copy_targeter',
978 sub copy_hold_capture {
983 if (!defined($cps)) {
985 $cps = [ asset::copy->search( id => $hold->target ) ];
988 die "Could not retrieve initial volume list:\n\n$e\n";
992 my @copies = grep { $_->holdable } @$cps;
994 for (my $i = 0; $i < @$cps; $i++) {
995 next unless $$cps[$i];
997 my $cn = $cache{cns}{$copies[$i]->call_number};
998 my $rec = $cache{titles}{$cn->record};
999 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1000 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1001 $copies[$i] = undef if (
1003 !$self->{user_filter}->request(
1004 'open-ils.circ.permit_hold',
1005 $hold->to_fieldmapper, do {
1006 my $cp_fm = $copies[$i]->to_fieldmapper;
1007 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1008 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1009 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1012 { title => $rec->to_fieldmapper,
1013 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1014 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1017 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1020 @copies = grep { $_ } @copies;
1022 my $count = @copies;
1024 return unless ($count);
1026 action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
1029 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1030 for my $c (@copies) {
1031 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1033 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1039 sub choose_nearest_copy {
1041 my $prox_list = shift;
1043 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1044 next unless (ref $$prox_list[$p]);
1046 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1047 next unless (@capturable);
1049 my $rand = int(rand(scalar(@capturable)));
1050 while (my ($c) = splice(@capturable,$rand)) {
1051 unless ( OpenILS::Utils::PermitHold::permit_copy_hold(
1052 { title => $c->call_number->record->to_fieldmapper,
1053 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1054 patron => $hold->usr->to_fieldmapper,
1055 copy => $c->to_fieldmapper,
1056 requestor => $hold->requestor->to_fieldmapper,
1057 request_lib => $hold->request_lib->to_fieldmapper,
1060 last unless(@capturable);
1061 $rand = int(rand(scalar(@capturable)));
1069 sub create_prox_list {
1075 for my $cp (@$copies) {
1076 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1077 next unless (defined($prox));
1078 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1079 push @{$prox_list[$prox]}, $cp;
1084 sub volume_hold_capture {
1089 if (!defined($vols)) {
1091 $vols = [ asset::call_number->search( id => $hold->target ) ];
1092 $cache{cns}{$_->id} = $_ for (@$vols);
1093 } catch Error with {
1095 die "Could not retrieve initial volume list:\n\n$e\n";
1099 my @v_ids = map { $_->id } @$vols;
1103 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1105 } catch Error with {
1107 warn "Could not retrieve copy list:\n\n$e\n";
1110 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1113 sub title_hold_capture {
1118 if (!defined($titles)) {
1120 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1121 $cache{titles}{$_->id} = $_ for (@$titles);
1122 } catch Error with {
1124 die "Could not retrieve initial title list:\n\n$e\n";
1128 my @t_ids = map { $_->id } @$titles;
1131 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1133 } catch Error with {
1135 warn "Could not retrieve volume list:\n\n$e\n";
1138 $cache{cns}{$_->id} = $_ for (@$cn_list);
1140 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1143 sub metarecord_hold_capture {
1149 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1151 } catch Error with {
1153 die "Could not retrieve initial title list:\n\n$e\n";
1157 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1159 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1161 } catch Error with {
1163 die "Could not retrieve format-pruned title list:\n\n$e\n";
1167 $cache{titles}{$_->id} = $_ for (@$titles);
1168 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);