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 if (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');
525 my $timestamptz = $billing_ts->strftime('%FT%T%z');
526 my @cl = actor::org_unit::closed_date->search_where(
527 { close_start => { '<=' => $timestamptz },
528 close_end => { '>=' => $timestamptz },
529 org_unit => $c->circ_lib }
533 my $billing = money::billing->create(
535 note => "Overdue Fine",
536 billing_type => "Overdue materials",
537 amount => ''.$c->recuring_fine,
538 billing_ts => $timestamptz,
543 "\t\tCreating fine of ".$billing->amount." for period starting ".
545 $parser->parse_datetime(
546 clense_ISO8601( $billing->billing_ts )
552 'open-ils.penalty.patron_penalty.calculate',
553 { patron => $c->usr->to_fieldmapper,
561 $client->respond( "Error processing overdue circulation [".$c->id."]:\n\n$e\n" );
565 __PACKAGE__->register_method(
566 api_name => 'open-ils.storage.action.circulation.overdue.generate_fines',
569 method => 'generate_fines',
574 sub new_hold_copy_targeter {
577 my $check_expire = shift;
578 my $one_hold = shift;
580 local $OpenILS::Application::Storage::WRITE = 1;
586 $holds = [ action::hold_request->search_where( { id => $one_hold, fulfillment_time => undef } ) ];
587 } elsif ( $check_expire ) {
590 $check_expire ||= '12h';
591 $check_expire = interval_to_seconds( $check_expire );
593 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
596 my $expire_threshold = sprintf(
597 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
598 $year, $mon, $mday, $hour, $min, $sec
601 $holds = [ action::hold_request->search_where(
602 { capture_time => undef,
603 fulfillment_time => undef,
604 prev_check_time => { '<=' => $expire_threshold },
606 { order_by => 'selection_depth DESC, request_time,prev_check_time' } ) ];
607 push @$holds, action::hold_request->search(
608 capture_time => undef,
609 fulfillment_time => undef,
610 prev_check_time => undef,
611 { order_by => 'selection_depth DESC, request_time' } );
613 $holds = [ action::hold_request->search(
614 capture_time => undef,
615 fulfillment_time => undef,
616 prev_check_time => undef,
617 { order_by => 'selection_depth DESC, request_time' } ) ];
621 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
626 for my $hold (@$holds) {
628 #action::hold_request->db_Main->begin_work;
629 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
630 $log->debug("Cleaning up after previous transaction\n");
631 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
633 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
634 $log->info("Processing hold ".$hold->id."...\n");
636 action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
640 my ($types, $formats, $lang) = split '-', $hold->holdable_formats;
642 # find all the potential copies
643 if ($hold->hold_type eq 'M') {
646 metabib::record_descriptor
648 record => [ map { $_->id } metabib::metarecord->retrieve($hold->target)->source_records ],
649 ( $types ? (item_type => [split '', $types]) : () ),
650 ( $formats ? (item_form => [split '', $formats]) : () ),
651 ( $lang ? (item_lang => $lang) : () ),
655 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
656 ->run( $r->id, $hold->selection_ou, $hold->selection_depth );
658 for my $cn ( @{ $rtree->call_numbers } ) {
660 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
663 } elsif ($hold->hold_type eq 'T') {
665 ->method_lookup( 'open-ils.storage.biblio.record_entry.ranged_tree')
666 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
669 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_RECORD' };
673 for my $cn ( @{ $rtree->call_numbers } ) {
675 asset::copy->search( id => [map {$_->id} @{ $cn->copies }] );
677 } elsif ($hold->hold_type eq 'V') {
679 ->method_lookup( 'open-ils.storage.asset.call_number.ranged_tree')
680 ->run( $hold->target, $hold->selection_ou, $hold->selection_depth );
683 asset::copy->search( id => [map {$_->id} @{ $vtree->copies }] );
685 } elsif ($hold->hold_type eq 'C') {
687 $all_copies = [asset::copy->retrieve($hold->target)];
690 @$all_copies = grep { $_->status->holdable &&
691 $_->location->holdable &&
695 # let 'em know we're still working
696 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
698 if (!ref $all_copies || !@$all_copies) {
699 $log->info("\tNo copies available for targeting at all!\n");
700 $self->method_lookup('open-ils.storage.transaction.commit')->run;
701 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_COPIES' };
705 my $copy_count = @$all_copies;
707 # map the potentials, so that we can pick up checkins
708 $log->debug( "\tMapping ".scalar(@$all_copies)." potential copies for hold ".$hold->id);
709 action::hold_copy_map->create( { hold => $hold->id, target_copy => $_->id } ) for (@$all_copies);
711 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
714 for my $c (@$all_copies) {
715 next if ($c->id == $hold->current_copy);
716 next if (action::hold_request
718 { current_copy => $c->id,
719 capture_time => undef,
723 push @good_copies, $c if ($c);
724 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
727 $log->debug("\t".scalar(@good_copies)." (non-current) copies available for targeting...");
729 my $old_best = $hold->current_copy;
730 $hold->update({ current_copy => undef });
732 if (!scalar(@good_copies)) {
733 $log->info("\tNo (non-current) copies eligible to fill the hold.");
736 grep { $old_best eq $_ } @$all_copies &&
737 !action::hold_request->search_where({ current_copy => $old_best->id, capture_time => undef })
739 $log->debug("\tPushing current_copy back onto the targeting list");
740 push @good_copies, $old_best;
742 $log->debug("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!");
743 $self->method_lookup('open-ils.storage.transaction.commit')->run;
744 push @successes, { hold => $hold->id, eligible_copies => 0, error => 'NO_TARGETS' };
749 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
754 $_->circ_lib == $hold->pickup_lib
758 $all_copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
760 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
761 my $best = choose_nearest_copy($hold, $prox_list);
762 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
765 $log->debug("\tNothing at the pickup lib, looking elsewhere among ".scalar(@$all_copies)." copies");
766 $prox_list = create_prox_list( $self, $hold->pickup_lib, $all_copies );
768 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
770 $best = choose_nearest_copy($hold, $prox_list);
773 $client->status( new OpenSRF::DomainObject::oilsContinueStatus );
775 # hold wasn't fulfilled, record the fact
777 $log->info("\tHold was not (but should have been) fulfilled by ".$old_best->id);
778 action::unfulfilled_hold_list->create(
779 { hold => ''.$hold->id,
780 current_copy => ''.$old_best->id,
781 circ_lib => ''.$old_best->circ_lib,
786 $hold->update( { current_copy => ''.$best->id } );
787 $log->debug("\tUpdating hold [".$hold->id."] with new 'current_copy' [".$best->id."] for hold fulfillment.");
789 $log->info( "\tThere were no targetable copies for the hold" );
792 $hold->update( { prev_check_time => 'now' } );
794 $self->method_lookup('open-ils.storage.transaction.commit')->run;
795 $log->info("\tProcessing of hold ".$hold->id." complete.");
799 old_target => ($old_best ? $old_best->id : undef),
800 eligible_copies => $copy_count,
801 target => ($best ? $best->id : undef) };
806 $log->error("Processing of hold failed: $e");
807 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
814 __PACKAGE__->register_method(
815 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
817 method => 'new_hold_copy_targeter',
822 my %cache = (titles => {}, cns => {});
823 sub hold_copy_targeter {
826 my $check_expire = shift;
827 my $one_hold = shift;
829 $self->{user_filter} = OpenSRF::AppSession->create('open-ils.circ');
830 $self->{user_filter}->connect;
831 $self->{client} = $client;
834 $check_expire ||= '12h';
835 $check_expire = interval_to_seconds( $check_expire );
837 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time() - $check_expire);
840 my $expire_threshold = sprintf(
841 '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
842 $year, $mon, $mday, $hour, $min, $sec
846 $statuses ||= [ config::copy_status->search(holdable => 't') ];
848 $locations ||= [ asset::copy_location->search(holdable => 't') ];
852 %cache = (titles => {}, cns => {});
856 $holds = [ action::hold_request->search(id => $one_hold) ];
858 $holds = [ action::hold_request->search_where(
859 { capture_time => undef,
860 prev_check_time => { '<=' => $expire_threshold },
862 { order_by => 'request_time,prev_check_time' } ) ];
863 push @$holds, action::hold_request->search(
864 capture_time => undef,
865 prev_check_time => undef,
866 { order_by => 'request_time' } );
870 die "Could not retrieve uncaptured hold requests:\n\n$e\n";
873 for my $hold (@$holds) {
875 #action::hold_request->db_Main->begin_work;
876 if ($self->method_lookup('open-ils.storage.transaction.current')->run) {
877 $client->respond("Cleaning up after previous transaction\n");
878 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
880 $self->method_lookup('open-ils.storage.transaction.begin')->run( $client );
881 $client->respond("Processing hold ".$hold->id."...\n");
885 $copies = $self->metarecord_hold_capture($hold) if ($hold->hold_type eq 'M');
886 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
888 $copies = $self->title_hold_capture($hold) if ($hold->hold_type eq 'T');
889 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
891 $copies = $self->volume_hold_capture($hold) if ($hold->hold_type eq 'V');
892 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
894 $copies = $self->copy_hold_capture($hold) if ($hold->hold_type eq 'C');
896 unless (ref $copies || !@$copies) {
897 $client->respond("\tNo copies available for targeting at all!\n");
901 for my $c (@$copies) {
902 next if ( grep {$c->id == $hold->current_copy} @good_copies);
903 push @good_copies, $c if ($c);
906 $client->respond("\t".scalar(@good_copies)." (non-current) copies available for targeting...\n");
908 my $old_best = $hold->current_copy;
909 $hold->update({ current_copy => undef });
911 if (!scalar(@good_copies)) {
912 $client->respond("\tNo (non-current) copies available to fill the hold.\n");
913 if ( $old_best && grep {$c->id == $hold->current_copy} @$copies ) {
914 $client->respond("\tPushing current_copy back onto the targeting list\n");
915 push @good_copies, asset::copy->retrieve( $old_best );
917 $client->respond("\tcurrent_copy is no longer available for targeting... NEXT HOLD, PLEASE!\n");
923 $$prox_list[0] = [grep {$_->circ_lib == $hold->pickup_lib } @good_copies];
924 $copies = [grep {$_->circ_lib != $hold->pickup_lib } @good_copies];
926 my $best = choose_nearest_copy($hold, $prox_list);
929 $prox_list = create_prox_list( $self, $hold->pickup_lib, $copies );
930 $best = choose_nearest_copy($hold, $prox_list);
934 # hold wasn't fulfilled, record the fact
936 $client->respond("\tHold was not (but should have been) fulfilled by ".$old_best->id.".\n");
937 action::unfulfilled_hold_list->create(
938 { hold => ''.$hold->id,
939 current_copy => ''.$old_best->id,
940 circ_lib => ''.$old_best->circ_lib,
945 $hold->update( { current_copy => ''.$best->id } );
946 $client->respond("\tTargeting copy ".$best->id." for hold fulfillment.\n");
949 $hold->update( { prev_check_time => 'now' } );
950 $client->respond("\tUpdating hold ".$hold->id." with new 'current_copy' for hold fulfillment.\n");
952 $client->respond("\tProcessing of hold ".$hold->id." complete.\n");
953 $self->method_lookup('open-ils.storage.transaction.commit')->run;
955 #action::hold_request->dbi_commit;
959 $log->error("Processing of hold failed: $e");
960 $client->respond("\tProcessing of hold failed!.\n\t\t$e\n");
961 $self->method_lookup('open-ils.storage.transaction.rollback')->run;
962 #action::hold_request->dbi_rollback;
966 $self->{user_filter}->disconnect;
967 $self->{user_filter}->finish;
968 delete $$self{user_filter};
971 __PACKAGE__->register_method(
972 api_name => 'open-ils.storage.action.hold_request.copy_targeter',
975 method => 'hold_copy_targeter',
979 sub copy_hold_capture {
984 if (!defined($cps)) {
986 $cps = [ asset::copy->search( id => $hold->target ) ];
989 die "Could not retrieve initial volume list:\n\n$e\n";
993 my @copies = grep { $_->holdable } @$cps;
995 for (my $i = 0; $i < @$cps; $i++) {
996 next unless $$cps[$i];
998 my $cn = $cache{cns}{$copies[$i]->call_number};
999 my $rec = $cache{titles}{$cn->record};
1000 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->status eq $_->id}@$statuses);
1001 $copies[$i] = undef if ($copies[$i] && !grep{ $copies[$i]->location eq $_->id}@$locations);
1002 $copies[$i] = undef if (
1004 !$self->{user_filter}->request(
1005 'open-ils.circ.permit_hold',
1006 $hold->to_fieldmapper, do {
1007 my $cp_fm = $copies[$i]->to_fieldmapper;
1008 $cp_fm->circ_lib( $copies[$i]->circ_lib->to_fieldmapper );
1009 $cp_fm->location( $copies[$i]->location->to_fieldmapper );
1010 $cp_fm->status( $copies[$i]->status->to_fieldmapper );
1013 { title => $rec->to_fieldmapper,
1014 usr => actor::user->retrieve($hold->usr)->to_fieldmapper,
1015 requestor => actor::user->retrieve($hold->requestor)->to_fieldmapper,
1018 $self->{client}->status( new OpenSRF::DomainObject::oilsContinueStatus );
1021 @copies = grep { $_ } @copies;
1023 my $count = @copies;
1025 return unless ($count);
1027 action::hold_copy_map->search( { hold => $hold->id } )->delete_all;
1030 $self->{client}->respond( "\tMapping ".scalar(@copies)." eligable copies for hold ".$hold->id."\n");
1031 for my $c (@copies) {
1032 push @maps, action::hold_copy_map->create( { hold => $hold->id, target_copy => $c->id } );
1034 $self->{client}->respond( "\tA total of ".scalar(@maps)." mapping were created for hold ".$hold->id."\n");
1040 sub choose_nearest_copy {
1042 my $prox_list = shift;
1044 for my $p ( 0 .. int( scalar(@$prox_list) - 1) ) {
1045 next unless (ref $$prox_list[$p]);
1047 my @capturable = grep { $_->status == 0 || $_->status == 7 } @{ $$prox_list[$p] };
1048 next unless (@capturable);
1050 my $rand = int(rand(scalar(@capturable)));
1051 while (my ($c) = splice(@capturable,$rand)) {
1052 unless ( OpenILS::Utils::PermitHold::permit_copy_hold(
1053 { title => $c->call_number->record->to_fieldmapper,
1054 title_descriptor => $c->call_number->record->record_descriptor->next->to_fieldmapper,
1055 patron => $hold->usr->to_fieldmapper,
1056 copy => $c->to_fieldmapper,
1057 requestor => $hold->requestor->to_fieldmapper,
1058 request_lib => $hold->request_lib->to_fieldmapper,
1061 last unless(@capturable);
1062 $rand = int(rand(scalar(@capturable)));
1070 sub create_prox_list {
1076 for my $cp (@$copies) {
1077 my ($prox) = $self->method_lookup('open-ils.storage.asset.copy.proximity')->run( $cp, $lib );
1078 next unless (defined($prox));
1079 $prox_list[$prox] = [] unless defined($prox_list[$prox]);
1080 push @{$prox_list[$prox]}, $cp;
1085 sub volume_hold_capture {
1090 if (!defined($vols)) {
1092 $vols = [ asset::call_number->search( id => $hold->target ) ];
1093 $cache{cns}{$_->id} = $_ for (@$vols);
1094 } catch Error with {
1096 die "Could not retrieve initial volume list:\n\n$e\n";
1100 my @v_ids = map { $_->id } @$vols;
1104 $cp_list = [ asset::copy->search( call_number => \@v_ids ) ];
1106 } catch Error with {
1108 warn "Could not retrieve copy list:\n\n$e\n";
1111 $self->copy_hold_capture($hold,$cp_list) if (ref $cp_list and @$cp_list);
1114 sub title_hold_capture {
1119 if (!defined($titles)) {
1121 $titles = [ biblio::record_entry->search( id => $hold->target ) ];
1122 $cache{titles}{$_->id} = $_ for (@$titles);
1123 } catch Error with {
1125 die "Could not retrieve initial title list:\n\n$e\n";
1129 my @t_ids = map { $_->id } @$titles;
1132 ($cn_list) = $self->method_lookup('open-ils.storage.direct.asset.call_number.search.record.atomic')->run( \@t_ids );
1134 } catch Error with {
1136 warn "Could not retrieve volume list:\n\n$e\n";
1139 $cache{cns}{$_->id} = $_ for (@$cn_list);
1141 $self->volume_hold_capture($hold,$cn_list) if (ref $cn_list and @$cn_list);
1144 sub metarecord_hold_capture {
1150 $titles = [ metabib::metarecord_source_map->search( metarecord => $hold->target) ];
1152 } catch Error with {
1154 die "Could not retrieve initial title list:\n\n$e\n";
1158 my @recs = map {$_->record} metabib::record_descriptor->search( record => $titles, item_type => [split '', $hold->holdable_formats] );
1160 $titles = [ biblio::record_entry->search( id => \@recs ) ];
1162 } catch Error with {
1164 die "Could not retrieve format-pruned title list:\n\n$e\n";
1168 $cache{titles}{$_->id} = $_ for (@$titles);
1169 $self->title_hold_capture($hold,$titles) if (ref $titles and @$titles);